{"version":3,"file":"global.js","names":["global","factory","exports","module","define","amd","globalThis","self","DOMPurify","this","entries","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","Object","freeze","seal","create","apply","construct","Reflect","x","fun","thisValue","args","Func","arrayForEach","unapply","Array","prototype","forEach","arrayPop","pop","arrayPush","push","stringToLowerCase","String","toLowerCase","stringToString","toString","stringMatch","match","stringReplace","replace","stringIndexOf","indexOf","stringTrim","trim","objectHasOwnProperty","hasOwnProperty","regExpTest","RegExp","test","typeErrorCreate","unconstruct","TypeError","func","thisArg","_len","arguments","length","_key","_len2","_key2","addToSet","set","array","transformCaseFunc","undefined","l","element","lcElement","cleanArray","index","isPropertyExist","clone","object","newObject","property","value","isArray","constructor","lookupGetter","prop","desc","get","fallbackValue","html$1","svg$1","svgFilters","svgDisallowed","mathMl$1","mathMlDisallowed","text","html","svg","mathMl","xml","MUSTACHE_EXPR","ERB_EXPR","TMPLIT_EXPR","DATA_ATTR","ARIA_ATTR","IS_ALLOWED_URI","IS_SCRIPT_OR_DATA","ATTR_WHITESPACE","DOCTYPE_NAME","CUSTOM_ELEMENT","EXPRESSIONS","__proto__","NODE_TYPE","attribute","cdataSection","entityReference","entityNode","progressingInstruction","comment","document","documentType","documentFragment","notation","getGlobal","window","_createTrustedTypesPolicy","trustedTypes","purifyHostElement","createPolicy","suffix","ATTR_NAME","hasAttribute","getAttribute","policyName","createHTML","createScriptURL","scriptUrl","_","console","warn","_createHooksMap","afterSanitizeAttributes","afterSanitizeElements","afterSanitizeShadowDOM","beforeSanitizeAttributes","beforeSanitizeElements","beforeSanitizeShadowDOM","uponSanitizeAttribute","uponSanitizeElement","uponSanitizeShadowNode","createDOMPurify","root","version","removed","nodeType","isSupported","originalDocument","currentScript","DocumentFragment","HTMLTemplateElement","Node","Element","NodeFilter","NamedNodeMap","MozNamedAttrMap","HTMLFormElement","DOMParser","ElementPrototype","cloneNode","remove","getNextSibling","getChildNodes","getParentNode","template","createElement","content","ownerDocument","trustedTypesPolicy","emptyHTML","implementation","createNodeIterator","createDocumentFragment","getElementsByTagName","importNode","hooks","createHTMLDocument","IS_ALLOWED_URI$1","ALLOWED_TAGS","DEFAULT_ALLOWED_TAGS","ALLOWED_ATTR","DEFAULT_ALLOWED_ATTR","CUSTOM_ELEMENT_HANDLING","tagNameCheck","writable","configurable","enumerable","attributeNameCheck","allowCustomizedBuiltInElements","FORBID_TAGS","FORBID_ATTR","ALLOW_ARIA_ATTR","ALLOW_DATA_ATTR","ALLOW_UNKNOWN_PROTOCOLS","ALLOW_SELF_CLOSE_IN_ATTR","SAFE_FOR_TEMPLATES","SAFE_FOR_XML","WHOLE_DOCUMENT","SET_CONFIG","FORCE_BODY","RETURN_DOM","RETURN_DOM_FRAGMENT","RETURN_TRUSTED_TYPE","SANITIZE_DOM","SANITIZE_NAMED_PROPS","SANITIZE_NAMED_PROPS_PREFIX","KEEP_CONTENT","IN_PLACE","USE_PROFILES","FORBID_CONTENTS","DEFAULT_FORBID_CONTENTS","DATA_URI_TAGS","DEFAULT_DATA_URI_TAGS","URI_SAFE_ATTRIBUTES","DEFAULT_URI_SAFE_ATTRIBUTES","MATHML_NAMESPACE","SVG_NAMESPACE","HTML_NAMESPACE","NAMESPACE","IS_EMPTY_INPUT","ALLOWED_NAMESPACES","DEFAULT_ALLOWED_NAMESPACES","MATHML_TEXT_INTEGRATION_POINTS","HTML_INTEGRATION_POINTS","COMMON_SVG_AND_HTML_ELEMENTS","PARSER_MEDIA_TYPE","SUPPORTED_PARSER_MEDIA_TYPES","DEFAULT_PARSER_MEDIA_TYPE","CONFIG","formElement","isRegexOrFunction","testValue","Function","_parseConfig","cfg","ADD_URI_SAFE_ATTR","ADD_DATA_URI_TAGS","ALLOWED_URI_REGEXP","ADD_TAGS","ADD_ATTR","table","tbody","TRUSTED_TYPES_POLICY","ALL_SVG_TAGS","ALL_MATHML_TAGS","_checkValidNamespace","parent","tagName","namespaceURI","parentTagName","Boolean","_forceRemove","node","removeChild","_removeAttribute","name","getAttributeNode","from","removeAttribute","setAttribute","_initDocument","dirty","doc","leadingWhitespace","matches","dirtyPayload","parseFromString","documentElement","createDocument","innerHTML","body","insertBefore","createTextNode","childNodes","call","_createNodeIterator","SHOW_ELEMENT","SHOW_COMMENT","SHOW_TEXT","SHOW_PROCESSING_INSTRUCTION","SHOW_CDATA_SECTION","_isClobbered","nodeName","textContent","attributes","hasChildNodes","_isNode","_executeHooks","currentNode","data","hook","_sanitizeElements","allowedTags","firstElementChild","_isBasicCustomElement","parentNode","childCount","i","childClone","__removalCount","expr","_isValidAttribute","lcTag","lcName","_sanitizeAttributes","hookEvent","attrName","attrValue","keepAttr","allowedAttributes","forceKeepAttr","attr","getAttributeType","setAttributeNS","_sanitizeShadowDOM","fragment","shadowNode","shadowIterator","nextNode","sanitize","importedNode","returnNode","appendChild","firstChild","nodeIterator","shadowroot","shadowrootmode","serializedHTML","outerHTML","doctype","setConfig","clearConfig","isValidAttribute","tag","addHook","entryPoint","hookFunction","removeHook","removeHooks","removeAllHooks","purify","Dexie","extendStatics","d","b","p","__extends","__","__assign","assign","t","s","n","__spreadArray","to","pack","ar","slice","concat","_global","keys","Promise","extend","obj","extension","key","getProto","_hasOwn","hasOwn","props","proto","ownKeys","setProp","defineProperty","functionOrGetSet","options","derive","Child","Parent","bind","getPropertyDescriptor","pd","_slice","start","end","override","origFunc","overridedFactory","assert","Error","asap$1","fn","setImmediate","setTimeout","arrayToObject","extractor","reduce","result","item","nameAndValue","getByKeyPath","keyPath","rv","val","period","innerObj","substr","setByKeyPath","currentKeyPath","remainingKeyPath","isNaN","parseInt","splice","delByKeyPath","map","kp","shallowClone","m","flatten","a","intrinsicTypeNames","split","num","filter","intrinsicTypes","Set","cloneSimpleObjectTree","o","k","v","has","objectIsEmpty","circularRefs","deepClone","any","WeakMap","innerDeepClone","toStringTag","iteratorSymbol","Symbol","iterator","getIteratorOf","delArrayItem","NO_CHAR_ARRAY","getArrayOf","arrayLike","it","next","done","isAsyncFunction","dexieErrorNames","idbDomErrorNames","errorList","defaultTexts","VersionChanged","DatabaseClosed","Abort","TransactionInactive","MissingAPI","DexieError","msg","message","getMultiErrorMessage","failures","join","ModifyError","successCount","failedKeys","BulkError","pos","failuresByPos","errnames","BaseException","exceptions","fullName","msgOrInner","inner","Syntax","SyntaxError","Type","Range","RangeError","exceptionMap","mapError","domError","stack","fullNameExceptions","nop","mirror","pureFunctionChain","f1","f2","callBoth","on1","on2","hookCreatingChain","res","onsuccess","onerror","res2","hookDeletingChain","hookUpdatingChain","modifications","reverseStoppableEventChain","promisableChain","then","thiz","debug","location","href","setDebug","INTERNAL","ZONE_ECHO_LIMIT","_a$1","globalP","resolve","crypto","subtle","nativeP","digest","Uint8Array","resolvedNativePromise","nativePromiseProto","resolvedGlobalPromise","nativePromiseThen","NativePromise","patchGlobalPromise","schedulePhysicalTick","queueMicrotask","physicalTick","asap","callback","microtickQueue","needsNewPhysicalTick","isOutsideMicroTick","unhandledErrors","rejectingErrors","rejectionMapper","globalPSD","id","ref","unhandleds","onunhandled","pgp","env","finalize","PSD","numScheduledCalls","tickFinalizers","DexiePromise","_listeners","_lib","psd","_PSD","_state","_value","handleRejection","executePromiseTask","thenProp","microTaskId","totalEchoes","onFulfilled","onRejected","_this","possibleAwait","cleanup","decrementExpectedAwaits","reject","propagateToListener","Listener","nativeAwaitCompatibleWrap","_consoleTask","_then","catch","type","handler","err","PromiseReject","finally","onFinally","timeout","ms","Infinity","handle","Timeout","clearTimeout","snapShot","zone","all","values","onPossibleParallellAsync","remaining","race","newPSD","newScope","usePSD","scheduler","follow","zoneProps","run_at_end_of_this_or_next_physical_tick","allSettled","possiblePromises","results","status","reason","AggregateError","failure","withResolvers","promise","shouldExecuteTick","beginMicroTickScope","propagateAllListeners","endMicroTickScope","ex","addPossiblyUnhandledError","listeners","len","finalizePhysicalTick","listener","cb","callListener","ret","run","markErrorAsHandled","e","wasRootExec","callbacks","unhandledErrs","finalizers","finalizer","some","wrap","errorCatcher","outerScope","switchToZone","task","awaits","echoes","taskCounter","zoneStack","zoneEchoes","zone_id_counter","a1","a2","PromiseProp","incrementExpectedAwaits","possiblePromise","rejection","zoneEnterEcho","targetZone","zoneLeaveEcho","bEnteringZone","currentZone","GlobalPromise","targetEnv","a3","outerZone","execInGlobalContext","enqueueNativeMicroTask","tempTransaction","db","mode","storeNames","idbdb","openComplete","letThrough","_vip","dbOpenError","isBeingOpened","autoOpen","open","dbReadyPromise","trans","_createTransaction","_dbSchema","PR1398_maxLoop","InvalidState","isOpen","close","disableAutoOpen","_promise","idbtrans","commit","_a","_completion","DEXIE_VERSION","maxString","fromCharCode","minKey","INVALID_KEY_ARGUMENT","STRING_EXPECTED","connections","DBNAMES_DB","READONLY","READWRITE","combine","filter1","filter2","AnyRange","lower","lowerOpen","upper","upperOpen","workaroundForUndefinedPrimKey","Entity","cmp","ta","tb","NaN","compareUint8Arrays","getUint8Array","compareArrays","al","bl","ArrayBuffer","isView","tsTag","buffer","byteOffset","byteLength","Table","_trans","writeLocked","_tx","tableName","createTask","checkTableInTransaction","schema","NotFound","_novip","transless","trace","keyOrCrit","where","first","core","reading","fire","indexOrCrit","WhereClause","keyPaths","equals","compoundIndex","indexes","primKey","ix","compound","every","sort","_maxKey","keyPathsInValidOrder","JSON","stringify","idxByName","prevIndex","prevFilterFn","multi","idx","filterFunction","toCollection","and","count","thenShortcut","offset","limit","numRows","each","toArray","Collection","orderBy","reverse","mapToClass","mappedClass","_super","class_1","inheritedProps","getOwnPropertyNames","propName","add","readHook","unsubscribe","defineClass","Class","auto","objToAdd","mutate","numFailures","lastResult","update","keyOrObject","InvalidArgument","modify","put","delete","clear","range","bulkGet","getMany","bulkAdd","objects","keysOrOptions","wantResults","allKeys","numObjects","objectsToAdd","bulkPut","objectsToPut","bulkUpdate","keysAndChanges","coreTable","entry","changeSpecs","changes","offsetMap","cache","objs","resultKeys","resultObjs","_i","_b","Constraint","numEntries","updates","mappedOffset","Number","bulkDelete","numKeys","Events","ctx","evs","eventName","subscriber","subscribe","addEventType","chainFunction","defaultFunction","addConfiguredEvents","context","subscribers","fireEvent","makeClassConstructor","createTableConstructor","tableSchema","_allTables","creating","updating","deleting","isPlainKeyRange","ignoreLimitFilter","algorithm","or","justLimit","replayFilter","addFilter","addReplayFilter","isLimitFilter","curr","addMatchFilter","isMatch","getIndexOrStore","coreSchema","isPrimKey","primaryKey","getIndexByKeyPath","Schema","openCursor","keysOnly","dir","unique","query","iter","coreTrans","iterate","valueMapper","set_1","union","cursor","advance","stop","fail","_iterate","cursorPromise","mappedFn","c","wrappedFn","continue","advancer","PropModSymbol","PropModification","spec","execute","term","BigInt","subtrahend_1","includes","_c","prefixToReplace","replacePrefix","startsWith","substring","_read","_ctx","error","_write","_addAlgorithm","raw","Math","min","sortBy","parts","lastPart","lastIndex","getval","order","sorter","aVal","bVal","valueMapper_1","a_1","offsetLeft","rowsLeft","until","bIncludeStopEntry","last","indexName","_ondirectionchange","eachKey","eachUniqueKey","eachPrimaryKey","primaryKeys","uniqueKeys","firstKey","lastKey","distinct","strKey","found","modifyer","anythingModified","origVal","outbound","extractKey","modifyChunkSize","_options","totalFailures","applyMutateResult","expectedCount","criteria","deleteCallback","nextChunk","addValues","putValues","putKeys","deleteKeys","origValue","ctx_1","changeSpec","isAdditionalChunk","coreRange","createCollectionConstructor","whereClause","keyRangeGenerator","keyRange","whereCtx","readingHook","simpleCompare","simpleCompareReverse","collectionOrWhereClause","T","collection","emptyCollection","rangeEqual","upperFactory","toUpperCase","lowerFactory","nextCasing","lowerKey","upperNeedle","lowerNeedle","llp","lwrKeyChar","addIgnoreCaseAlgorithm","needles","compare","upperNeedles","lowerNeedles","direction","nextKeySuffix","needlesLen","initDirection","needleBounds","needle","nb","createRange","firstPossibleNeedle","lowestPossibleCasing","casing","between","includeLower","includeUpper","_cmp","above","aboveOrEqual","below","belowOrEqual","str","startsWithIgnoreCase","equalsIgnoreCase","anyOfIgnoreCase","startsWithAnyOfIgnoreCase","anyOf","_ascending","_descending","notEqual","inAnyRange","includeLowers","includeUppers","noneOf","ranges","ascending","descending","_min","max","_max","addRange","newRange","sortDirection","rangeSorter","rangePos","keyIsBeyondCurrentEntry","keyIsBeforeCurrentEntry","keyWithinCurrentRange","checkKey","startsWithAnyOf","createWhereClauseConstructor","orCollection","_IDBKeyRange","_deps","IDBKeyRange","eventRejectHandler","event","preventDefault","target","stopPropagation","DEXIE_STORAGE_MUTATED_EVENT_NAME","STORAGE_MUTATED_DOM_EVENT_NAME","globalEvents","Transaction","_lock","_reculock","lockOwnerFor","_unlock","_blockedFuncs","_locked","fnAndPSD","shift","OpenFailed","active","transaction","durability","chromeTransactionDurability","ev","_reject","onabort","on","oncomplete","_resolve","storagemutated","bWriteLock","ReadOnly","_root","waitFor","promiseLike","_waitingFor","_waitingQueue","store","objectStore","spin","_spinCount","currentWaitPromise","abort","memoizedTables","_memoizedTables","transactionBoundTable","createTransactionConstructor","dbschema","complete","wasActive","createIndexSpec","src","nameFromKeyPath","createTableSchema","safariMultiStoreFix","getMaxKey","IdbKeyRange","only","getKeyExtractor","getSinglePathKeyExtractor","arrayify","_id_counter","getKeyPathAlias","createDBCore","tmpTrans","extractSchema","tables","objectStoreNames","autoIncrement","indexByKeyPath","isPrimaryKey","indexNames","multiEntry","hasGetAll","navigator","userAgent","makeIDBKeyRange","idbRange","upperBound","lowerBound","bound","createDbCoreTable","isAddOrPut","req","reqs","errorHandler","args1","args2","source","openKeyCursor","___id","_cursorContinue","_cursorContinuePrimaryKey","continuePrimaryKey","_cursorAdvance","doThrowCursorIsNotStarted","doThrowCursorIsStopped","gotOne","iterationPromise","resolveIteration","rejectIteration","guardedCallback","request","nonInfinitLimit","idbKeyRange","getAll","getAllKeys","count_1","req_1","result_1","keyCount","callbackCount","successHandler","_pos","tableMap","MIN_KEY","MAX_KEY","createMiddlewareStack","stackImpl","middlewares","down","createMiddlewareStacks","indexedDB","dbcore","generateMiddlewareStacks","stacks","_middlewares","tbl","setApiOnPlace","tableNames","propDesc","removeTablesApi","lowerVersionFirst","_cfg","runUpgraders","oldVersion","idbUpgradeTrans","globalSchema","contains","$meta","parseIndexSyntax","_storeNames","rejectTransaction","createTable","populate","getExistingVersion","updateTablesAndIndexes","patchCurrentVersion","createMissingTables","createObjectStore","ceil","buildGlobalSchema","adjustToExistingIndexNames","diff","getSchemaDiff","_loop_1","tableChange","change","recreate","addIndex","state_1","metaVersion","queue","versions","_versions","versToRun","oldSchema","newSchema","tuple","Upgrade","store_1","deleteIndex","del","idxName","contentUpgrade","upgradeSchema_1","contentUpgradeIsAsync_1","returnValue_1","promiseFollowed","decrementor","deleteRemovedTables","deleteObjectStore","runQueue","oldDef","newDef","def","oldIndexes","newIndexes","oldIdx","newIdx","storeName","createIndex","dbStoreNames","j","idbindex","readGlobalSchema","verno","verifyInstalledSchema","installedSchema","ch","_hasGetAll","dexieName","indexSpec","WorkerGlobalScope","primKeyAndIndexes","indexNum","Version","_parseStoresSpec","stores","outSchema","storesSource","storesSpec","upgrade","upgradeFunction","createVersionConstructor","versionNumber","getDbNamesTable","dbNamesDB","Dexie$1","addons","dbnames","hasDatabasesNative","databases","getDatabaseNames","infos","info","_onDatabaseCreated","_onDatabaseDeleted","vip","idbReady","isSafari","userAgentData","intervalId","tryIdb","setInterval","clearInterval","isEmptyRange","RangeSet","fromOrTree","rangeSet","mergeRanges","addKey","addKeys","hasKey","getRangeSetIterator","left","right","r","rebalance","rightWasCutOff","newSet","_addRangeSet","rangesOverlap","rangeSet1","rangeSet2","i1","nextResult1","i2","nextResult2","state","keyProvided","up","rootClone","oldRootRight","computeDepth","extendObservabilitySet","part","obsSetsOverlap","os1","os2","unsignaledParts","isTaskEnqueued","signalSubscribersLazily","optimistic","signalSubscribersNow","updatedParts","deleteAffectedCacheEntries","queriesToSignal","tblCache","collectTableSubscribers","exec","dbName","requery","outQueriesToSignal","updatedEntryLists","queries","filteredEntries","entries_1","obsSet","_d","updatedEntryLists_1","_e","dexieOpen","openCanceller","nativeVerToOpen","round","schemaPatchMode","throwIfCancelled","resolveDbReady","dbReadyResolve","upgradeTransaction","wasCreated","tryOpenDB","autoSchema","onblocked","_fireOnBlocked","onupgradeneeded","allowEmptyDB","delreq","deleteDatabase","NoSuchDatabase","oldVer","pow","onversionchange","vcFired","onclose","onReadyBeingFired","ready","fireRemainders","remainders_1","_close","everything_1","awaitIterator","callNext","doThrow","throw","onSuccess","step","onError","getNext","extractTransactionArgs","_tableArgs_","scopeFunc","enterTransactionScope","parentTransaction","explicit","_explicit","scopeFuncIsAsync","returnValue","PrematureCommit","pad","createVirtualIndexMiddleware","indexLookup","allVirtualIndexes","addVirtualIndexes","keyTail","lowLevelIndex","keyPathAlias","indexList","keyLength","isVirtual","virtualIndex","virtualKeyPath","findBestIndex","translateRange","translateRequest","createVirtualCursor","_continue","virtualCursor","virtualIndexMiddleware","level","getObjectDiff","prfx","ap","bp","apTypeName","bpTypeName","getEffectiveKeys","hooksMiddleware","downCore","downTable","tableMiddleware","dxTrans","addPutOrDelete","deleteRange","getExistingValues","existingValues","contexts","existingValue","generatedPrimaryKey","objectDiff","additionalChanges_1","requestedValue_1","deleteNextChunk","effectiveKeys","getFromTransactionCache","cacheExistingValuesMiddleware","cachedResult","isCachableContext","subscr","isCachableRequest","observabilityMiddleware","FULL_RANGE","querier","indexesWithAutoIncPK","tableClone","mutatedParts","getRangeSet","pkRangeSet","delsRangeSet","newObjs","oldCache","oldObjs","trackAffectedIndexes","idxVals","pkPos","findIndex","getRange","readSubscribers","method","isLiveQuery","cachable","pkRangeSet_1","delsRangeSet_1","queriedIndex","queriedRanges","keysPromise_1","resultingKeys","pKeys","cursor_1","wantValues_1","pkey","addAffectedIndex","addKeyOrKeys","oldKey","newKey","adjustOptimisticFromFailures","numBulkOps","isAboveLower","isBelowUpper","isWithinRange","applyOptimisticOps","ops","cacheEntry","immutable","queryRange","extractPrimKey","extractIndex","extractLowLevelIndex","finalResult","op","modifedResult","includedValues","includedPKs","pk","existingKeys_1","keySet_1","keysToDelete_1","range_1","areRangesEqual","r1","r2","compareLowers","lower1","lower2","lowerOpen1","lowerOpen2","compareUppers","upper1","upper2","upperOpen1","upperOpen2","isSuperRange","findCompatibleQuery","equalEntry","find","superEntry","countQuery","subscribeToCacheEntry","container","signal","addEventListener","size","enqueForDeletion","cacheMiddleware","coreMW","ac_1","AbortController","endTransaction","wasCommitted","affectedSubscribers_1","stores_1","optimisticOps","_f","_g","_h","freezeResults","modRes","tableMW","reqWithResolvedKeys","valueWithKey","adjustedReq","exactMatch","Map","vipify","vipDb","Proxy","receiver","deps","dependencies","cancelOpen","bSticky","db_1","newVersion","use","vipDB","tx","addon","versionInstance","_whenReady","unuse","mw","closeOptions","hasInvalidArguments","doDelete","backendDB","hasBeenClosed","hasFailed","dynamicallyOpened","_transaction","onlyIfCompatible","idbMode","SubTransaction","enterTransaction","InvalidTable","symbolObservable","observable","Observable","_subscribe","domDeps","mozIndexedDB","webkitIndexedDB","msIndexedDB","webkitIDBKeyRange","liveQuery","hasValue","currentValue","observer","closed","abortController","accumMuts","currentObs","subscription","startedListening","mutationListener","doQuery","_doQuery","shouldNotify","aborted","getValue","databaseName","exists","ignoreTransaction","async","generatorFn","spawn","currentTransaction","promiseOrFunction","optionalTimeout","semVer","maxKey","dispatchEvent","propagatingLocally","event_1","CustomEvent","detail","propagateLocally","updateParts","wasMe","bc","createBC","BroadcastChannel","onmessage","unref","changedParts","postMessage","disableBfCache","persisted","connections_1","namedExports","default","indexedDatabase","formTypes","formTypeUsers","attachments","forms","webforms","syncedForms","organizationUnits","Date","addSeconds","seconds","setSeconds","getSeconds","addMinutes","minutes","setMinutes","getMinutes","addHours","hours","setHours","getHours","addDays","days","setDate","getDate","addWeeks","weeks","addMonths","months","dt","setMonth","getMonth","currDt","addYears","years","setFullYear","getFullYear"],"sources":["../../../node_modules/dompurify/dist/purify.js","../../../node_modules/dexie/dist/dexie.js","../../../scripts/leanforms/indexedDB.js","../../../scripts/leanforms/date-functions.js"],"sourcesContent":["/*! @license DOMPurify 3.2.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.3/LICENSE */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DOMPurify = factory());\n})(this, (function () { 'use strict';\n\n const {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor\n } = Object;\n let {\n freeze,\n seal,\n create\n } = Object; // eslint-disable-line import/no-mutable-exports\n let {\n apply,\n construct\n } = typeof Reflect !== 'undefined' && Reflect;\n if (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n }\n if (!seal) {\n seal = function seal(x) {\n return x;\n };\n }\n if (!apply) {\n apply = function apply(fun, thisValue, args) {\n return fun.apply(thisValue, args);\n };\n }\n if (!construct) {\n construct = function construct(Func, args) {\n return new Func(...args);\n };\n }\n const arrayForEach = unapply(Array.prototype.forEach);\n const arrayPop = unapply(Array.prototype.pop);\n const arrayPush = unapply(Array.prototype.push);\n const stringToLowerCase = unapply(String.prototype.toLowerCase);\n const stringToString = unapply(String.prototype.toString);\n const stringMatch = unapply(String.prototype.match);\n const stringReplace = unapply(String.prototype.replace);\n const stringIndexOf = unapply(String.prototype.indexOf);\n const stringTrim = unapply(String.prototype.trim);\n const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\n const regExpTest = unapply(RegExp.prototype.test);\n const typeErrorCreate = unconstruct(TypeError);\n /**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\n function unapply(func) {\n return function (thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n return apply(func, thisArg, args);\n };\n }\n /**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\n function unconstruct(func) {\n return function () {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n return construct(func, args);\n };\n }\n /**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\n function addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n }\n /**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\n function cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n }\n /**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\n function clone(object) {\n const newObject = create(null);\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n }\n /**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\n function lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n }\n\n const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\n const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\n const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n // List of SVG elements that are disallowed by default.\n // We still need to know them so that we can do namespace\n // checks properly in case one wants to add them to\n // allow-list.\n const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\n const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n // Similarly to SVG, we want to know all MathML elements,\n // even those that we disallow by default.\n const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\n const text = freeze(['#text']);\n\n const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);\n const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\n const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\n const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\n // eslint-disable-next-line unicorn/better-regex\n const MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\n const ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\n const TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*}/gm); // eslint-disable-line unicorn/better-regex\n const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\n const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\n const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n );\n const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\n const ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n );\n const DOCTYPE_NAME = seal(/^html$/i);\n const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n\n var EXPRESSIONS = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ARIA_ATTR: ARIA_ATTR,\n ATTR_WHITESPACE: ATTR_WHITESPACE,\n CUSTOM_ELEMENT: CUSTOM_ELEMENT,\n DATA_ATTR: DATA_ATTR,\n DOCTYPE_NAME: DOCTYPE_NAME,\n ERB_EXPR: ERB_EXPR,\n IS_ALLOWED_URI: IS_ALLOWED_URI,\n IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,\n MUSTACHE_EXPR: MUSTACHE_EXPR,\n TMPLIT_EXPR: TMPLIT_EXPR\n });\n\n /* eslint-disable @typescript-eslint/indent */\n // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\n const NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n };\n const getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n };\n /**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\n const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n };\n const _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n };\n function createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.2.3';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let {\n document\n } = window;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes\n } = window;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName\n } = document;\n const {\n importNode\n } = originalDocument;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT\n } = EXPRESSIONS;\n let {\n IS_ALLOWED_URI: IS_ALLOWED_URI$1\n } = EXPRESSIONS;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with ... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n if (cfg.ADD_ATTR) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n }\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '' + dirty + '';\n }\n const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');\n };\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function _isNode(value) {\n return typeof Node === 'function' && value instanceof Node;\n };\n function _executeHooks(hooks, currentNode, data) {\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function _sanitizeElements(currentNode) {\n let content = null;\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* Detect mXSS attempts abusing namespace confusion */\n if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\\w]/g, currentNode.innerHTML) && regExpTest(/<[/\\w]/g, currentNode.textContent)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\\w]/g, currentNode.data)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n }\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n content = stringReplace(content, expr, ' ');\n });\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const {\n attributes\n } = currentNode;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const {\n name,\n namespaceURI,\n value: attrValue\n } = attr;\n const lcName = transformCaseFunc(name);\n let value = name === 'value' ? attrValue : stringTrim(attrValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|title)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Remove attribute */\n _removeAttribute(name, currentNode);\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n value = stringReplace(value, expr, ' ');\n });\n }\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n continue;\n }\n /* Handle attributes that require Trusted Types */\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {\n if (namespaceURI) ; else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n case 'TrustedScriptURL':\n {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n }\n }\n }\n /* Handle invalid data-* attribute set by try-catching it */\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {}\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if (dirty.nodeName) {\n const tagName = transformCaseFunc(dirty.nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n /* Now start iterating over the created document */\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint) {\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n }\n var purify = createDOMPurify();\n\n return purify;\n\n}));\n//# sourceMappingURL=purify.js.map\n","/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * By David Fahlander, david.fahlander@gmail.com\n *\n * Version 4.0.10, Fri Nov 15 2024\n *\n * https://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n */\n \n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Dexie = factory());\n})(this, (function () { 'use strict';\n\n /*! *****************************************************************************\n Copyright (c) Microsoft Corporation.\n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted.\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n PERFORMANCE OF THIS SOFTWARE.\n ***************************************************************************** */\n var extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n }\n var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n };\n function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n }\n\n var _global = typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\n var keys = Object.keys;\n var isArray = Array.isArray;\n if (typeof Promise !== 'undefined' && !_global.Promise) {\n _global.Promise = Promise;\n }\n function extend(obj, extension) {\n if (typeof extension !== 'object')\n return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n }\n var getProto = Object.getPrototypeOf;\n var _hasOwn = {}.hasOwnProperty;\n function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n }\n function props(proto, extension) {\n if (typeof extension === 'function')\n extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(function (key) {\n setProp(proto, key, extension[key]);\n });\n }\n var defineProperty = Object.defineProperty;\n function setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } :\n { value: functionOrGetSet, configurable: true, writable: true }, options));\n }\n function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n }\n var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n function getPropertyDescriptor(obj, prop) {\n var pd = getOwnPropertyDescriptor(obj, prop);\n var proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);\n }\n var _slice = [].slice;\n function slice(args, start, end) {\n return _slice.call(args, start, end);\n }\n function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n }\n function assert(b) {\n if (!b)\n throw new Error(\"Assertion Failed\");\n }\n function asap$1(fn) {\n if (_global.setImmediate)\n setImmediate(fn);\n else\n setTimeout(fn, 0);\n }\n function arrayToObject(array, extractor) {\n return array.reduce(function (result, item, i) {\n var nameAndValue = extractor(item, i);\n if (nameAndValue)\n result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n }\n function getByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath))\n return obj[keyPath];\n if (!keyPath)\n return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj == null ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n }\n function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined)\n return;\n if ('isFrozen' in Object && Object.isFrozen(obj))\n return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n }\n else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath)))\n obj.splice(currentKeyPath, 1);\n else\n delete obj[currentKeyPath];\n }\n else\n obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath))\n innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n }\n else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath)))\n obj.splice(keyPath, 1);\n else\n delete obj[keyPath];\n }\n else\n obj[keyPath] = value;\n }\n }\n }\n function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function (kp) {\n setByKeyPath(obj, kp, undefined);\n });\n }\n function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m))\n rv[m] = obj[m];\n }\n return rv;\n }\n var concat = [].concat;\n function flatten(a) {\n return concat.apply([], a);\n }\n var intrinsicTypeNames = \"BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return [\"Int\", \"Uint\", \"Float\"].map(function (t) { return t + num + \"Array\"; }); }))).filter(function (t) { return _global[t]; });\n var intrinsicTypes = new Set(intrinsicTypeNames.map(function (t) { return _global[t]; }));\n function cloneSimpleObjectTree(o) {\n var rv = {};\n for (var k in o)\n if (hasOwn(o, k)) {\n var v = o[k];\n rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v);\n }\n return rv;\n }\n function objectIsEmpty(o) {\n for (var k in o)\n if (hasOwn(o, k))\n return false;\n return true;\n }\n var circularRefs = null;\n function deepClone(any) {\n circularRefs = new WeakMap();\n var rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n }\n function innerDeepClone(x) {\n if (!x || typeof x !== 'object')\n return x;\n var rv = circularRefs.get(x);\n if (rv)\n return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n }\n else if (intrinsicTypes.has(x.constructor)) {\n rv = x;\n }\n else {\n var proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n }\n var toString = {}.toString;\n function toStringTag(o) {\n return toString.call(o).slice(8, -1);\n }\n var iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\n var getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function (x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n } : function () { return null; };\n function delArrayItem(a, x) {\n var i = a.indexOf(x);\n if (i >= 0)\n a.splice(i, 1);\n return i >= 0;\n }\n var NO_CHAR_ARRAY = {};\n function getArrayOf(arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike))\n return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string')\n return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done)\n a.push(x.value);\n return a;\n }\n if (arrayLike == null)\n return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--)\n a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--)\n a[i] = arguments[i];\n return a;\n }\n var isAsyncFunction = typeof Symbol !== 'undefined'\n ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; }\n : function () { return false; };\n\n var dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n ];\n var idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n ];\n var errorList = dexieErrorNames.concat(idbDomErrorNames);\n var defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n };\n function DexieError(name, msg) {\n this.name = name;\n this.message = msg;\n }\n derive(DexieError).from(Error).extend({\n toString: function () { return this.name + \": \" + this.message; }\n });\n function getMultiErrorMessage(msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(function (key) { return failures[key].toString(); })\n .filter(function (v, i, s) { return s.indexOf(v) === i; })\n .join('\\n');\n }\n function ModifyError(msg, failures, successCount, failedKeys) {\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n }\n derive(ModifyError).from(DexieError);\n function BulkError(msg, failures) {\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; });\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n }\n derive(BulkError).from(DexieError);\n var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + \"Error\", obj); }, {});\n var BaseException = DexieError;\n var exceptions = errorList.reduce(function (obj, name) {\n var fullName = name + \"Error\";\n function DexieError(msgOrInner, inner) {\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n }\n else if (typeof msgOrInner === 'string') {\n this.message = \"\".concat(msgOrInner).concat(!inner ? '' : '\\n ' + inner);\n this.inner = inner || null;\n }\n else if (typeof msgOrInner === 'object') {\n this.message = \"\".concat(msgOrInner.name, \" \").concat(msgOrInner.message);\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name] = DexieError;\n return obj;\n }, {});\n exceptions.Syntax = SyntaxError;\n exceptions.Type = TypeError;\n exceptions.Range = RangeError;\n var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n }, {});\n function mapError(domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n setProp(rv, \"stack\", { get: function () {\n return this.inner.stack;\n } });\n }\n return rv;\n }\n var fullNameExceptions = errorList.reduce(function (obj, name) {\n if ([\"Syntax\", \"Type\", \"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n }, {});\n fullNameExceptions.ModifyError = ModifyError;\n fullNameExceptions.DexieError = DexieError;\n fullNameExceptions.BulkError = BulkError;\n\n function nop() { }\n function mirror(val) { return val; }\n function pureFunctionChain(f1, f2) {\n if (f1 == null || f1 === mirror)\n return f2;\n return function (val) {\n return f2(f1(val));\n };\n }\n function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n }\n function hookCreatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined)\n arguments[0] = res;\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n }\n function hookDeletingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n }\n function hookUpdatingChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res);\n var onsuccess = this.onsuccess,\n onerror = this.onerror;\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess)\n this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror)\n this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n }\n function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n if (f2.apply(this, arguments) === false)\n return false;\n return f1.apply(this, arguments);\n };\n }\n function promisableChain(f1, f2) {\n if (f1 === nop)\n return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n }\n\n var debug = typeof location !== 'undefined' &&\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n function setDebug(value, filter) {\n debug = value;\n }\n\n var INTERNAL = {};\n var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ?\n [] :\n (function () {\n var globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n var nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\n var patchGlobalPromise = !!resolvedGlobalPromise;\n function schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n }\n var asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n };\n var isOutsideMicroTick = true,\n needsNewPhysicalTick = true,\n unhandledErrors = [],\n rejectingErrors = [],\n rejectionMapper = mirror;\n var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop\n };\n var PSD = globalPSD;\n var microtickQueue = [];\n var numScheduledCalls = 0;\n var tickFinalizers = [];\n function DexiePromise(fn) {\n if (typeof this !== 'object')\n throw new TypeError('Promises must be constructed via new');\n this._listeners = [];\n this._lib = false;\n var psd = (this._PSD = PSD);\n if (typeof fn !== 'function') {\n if (fn !== INTERNAL)\n throw new TypeError('Not a function');\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value);\n return;\n }\n this._state = null;\n this._value = null;\n ++psd.ref;\n executePromiseTask(this, fn);\n }\n var thenProp = {\n get: function () {\n var psd = PSD, microTaskId = totalEchoes;\n function then(onFulfilled, onRejected) {\n var _this = this;\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n var cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise(function (resolve, reject) {\n propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd));\n });\n if (this._consoleTask)\n rv._consoleTask = this._consoleTask;\n return rv;\n }\n then.prototype = INTERNAL;\n return then;\n },\n set: function (value) {\n setProp(this, 'then', value && value.prototype === INTERNAL ?\n thenProp :\n {\n get: function () {\n return value;\n },\n set: thenProp.set\n });\n }\n };\n props(DexiePromise.prototype, {\n then: thenProp,\n _then: function (onFulfilled, onRejected) {\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD));\n },\n catch: function (onRejected) {\n if (arguments.length === 1)\n return this.then(null, onRejected);\n var type = arguments[0], handler = arguments[1];\n return typeof type === 'function' ? this.then(null, function (err) {\n return err instanceof type ? handler(err) : PromiseReject(err);\n })\n : this.then(null, function (err) {\n return err && err.name === type ? handler(err) : PromiseReject(err);\n });\n },\n finally: function (onFinally) {\n return this.then(function (value) {\n return DexiePromise.resolve(onFinally()).then(function () { return value; });\n }, function (err) {\n return DexiePromise.resolve(onFinally()).then(function () { return PromiseReject(err); });\n });\n },\n timeout: function (ms, msg) {\n var _this = this;\n return ms < Infinity ?\n new DexiePromise(function (resolve, reject) {\n var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms);\n _this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n });\n if (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n globalPSD.env = snapShot();\n function Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n }\n props(DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments)\n .map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0)\n resolve([]);\n var remaining = values.length;\n values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) {\n values[i] = x;\n if (!--remaining)\n resolve(values);\n }, reject); });\n });\n },\n resolve: function (value) {\n if (value instanceof DexiePromise)\n return value;\n if (value && typeof value.then === 'function')\n return new DexiePromise(function (resolve, reject) {\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n return rv;\n },\n reject: PromiseReject,\n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve, reject) {\n values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); });\n });\n },\n PSD: {\n get: function () { return PSD; },\n set: function (value) { return PSD = value; }\n },\n totalEchoes: { get: function () { return totalEchoes; } },\n newPSD: newScope,\n usePSD: usePSD,\n scheduler: {\n get: function () { return asap; },\n set: function (value) { asap = value; }\n },\n rejectionMapper: {\n get: function () { return rejectionMapper; },\n set: function (value) { rejectionMapper = value; }\n },\n follow: function (fn, zoneProps) {\n return new DexiePromise(function (resolve, reject) {\n return newScope(function (resolve, reject) {\n var psd = PSD;\n psd.unhandleds = [];\n psd.onunhandled = reject;\n psd.finalize = callBoth(function () {\n var _this = this;\n run_at_end_of_this_or_next_physical_tick(function () {\n _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n });\n if (NativePromise) {\n if (NativePromise.allSettled)\n setProp(DexiePromise, \"allSettled\", function () {\n var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve) {\n if (possiblePromises.length === 0)\n resolve([]);\n var remaining = possiblePromises.length;\n var results = new Array(remaining);\n possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: \"fulfilled\", value: value }; }, function (reason) { return results[i] = { status: \"rejected\", reason: reason }; })\n .then(function () { return --remaining || resolve(results); }); });\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined')\n setProp(DexiePromise, \"any\", function () {\n var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(function (resolve, reject) {\n if (possiblePromises.length === 0)\n reject(new AggregateError([]));\n var remaining = possiblePromises.length;\n var failures = new Array(remaining);\n possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) {\n failures[i] = failure;\n if (!--remaining)\n reject(new AggregateError(failures));\n }); });\n });\n });\n if (NativePromise.withResolvers)\n DexiePromise.withResolvers = NativePromise.withResolvers;\n }\n function executePromiseTask(promise, fn) {\n try {\n fn(function (value) {\n if (promise._state !== null)\n return;\n if (value === promise)\n throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, function (resolve, reject) {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n }\n else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick)\n endMicroTickScope();\n }, handleRejection.bind(null, promise));\n }\n catch (ex) {\n handleRejection(promise, ex);\n }\n }\n function handleRejection(promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null)\n return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick)\n endMicroTickScope();\n }\n function propagateAllListeners(promise) {\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize();\n if (numScheduledCalls === 0) {\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n }\n }\n function propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n return (promise._state ? listener.resolve : listener.reject)(promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap(callListener, [cb, promise, listener]);\n }\n function callListener(cb, promise, listener) {\n try {\n var ret, value = promise._value;\n if (!promise._state && rejectingErrors.length)\n rejectingErrors = [];\n ret = debug && promise._consoleTask ? promise._consoleTask.run(function () { return cb(value); }) : cb(value);\n if (!promise._state && rejectingErrors.indexOf(value) === -1) {\n markErrorAsHandled(promise);\n }\n listener.resolve(ret);\n }\n catch (e) {\n listener.reject(e);\n }\n finally {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n }\n function physicalTick() {\n usePSD(globalPSD, function () {\n beginMicroTickScope() && endMicroTickScope();\n });\n }\n function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n }\n function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n }\n function finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(function (p) {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0);\n var i = finalizers.length;\n while (i)\n finalizers[--i]();\n }\n function run_at_end_of_this_or_next_physical_tick(fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(function () {\n if (--numScheduledCalls === 0)\n finalizePhysicalTick();\n }, []);\n }\n function addPossiblyUnhandledError(promise) {\n if (!unhandledErrors.some(function (p) { return p._value === promise._value; }))\n unhandledErrors.push(promise);\n }\n function markErrorAsHandled(promise) {\n var i = unhandledErrors.length;\n while (i)\n if (unhandledErrors[--i]._value === promise._value) {\n unhandledErrors.splice(i, 1);\n return;\n }\n }\n function PromiseReject(reason) {\n return new DexiePromise(INTERNAL, false, reason);\n }\n function wrap(fn, errorCatcher) {\n var psd = PSD;\n return function () {\n var wasRootExec = beginMicroTickScope(), outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n }\n catch (e) {\n errorCatcher && errorCatcher(e);\n }\n finally {\n switchToZone(outerScope, false);\n if (wasRootExec)\n endMicroTickScope();\n }\n };\n }\n var task = { awaits: 0, echoes: 0, id: 0 };\n var taskCounter = 0;\n var zoneStack = [];\n var zoneEchoes = 0;\n var totalEchoes = 0;\n var zone_id_counter = 0;\n function newScope(fn, props, a1, a2) {\n var parent = PSD, psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise,\n PromiseProp: { value: DexiePromise, configurable: true, writable: true },\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n } : {};\n if (props)\n extend(psd, props);\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n };\n var rv = usePSD(psd, fn, a1, a2);\n if (psd.ref === 0)\n psd.finalize();\n return rv;\n }\n function incrementExpectedAwaits() {\n if (!task.id)\n task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n }\n function decrementExpectedAwaits() {\n if (!task.awaits)\n return false;\n if (--task.awaits === 0)\n task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT;\n return true;\n }\n if (('' + nativePromiseThen).indexOf('[native code]') === -1) {\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n }\n function onPossibleParallellAsync(possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits();\n return possiblePromise.then(function (x) {\n decrementExpectedAwaits();\n return x;\n }, function (e) {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n }\n function zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.awaits = task.id = 0;\n }\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n }\n function zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length - 1];\n zoneStack.pop();\n switchToZone(zone, false);\n }\n function switchToZone(targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD)\n return;\n PSD = targetZone;\n if (currentZone === globalPSD)\n globalPSD.env = snapShot();\n if (patchGlobalPromise) {\n var GlobalPromise = globalPSD.env.Promise;\n var targetEnv = targetZone.env;\n if (currentZone.global || targetZone.global) {\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled)\n GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any)\n GlobalPromise.any = targetEnv.any;\n }\n }\n }\n function snapShot() {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n } : {};\n }\n function usePSD(psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n }\n finally {\n switchToZone(outerScope, false);\n }\n }\n function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait)\n incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n }\n finally {\n switchToZone(outerZone, false);\n if (cleanup)\n queueMicrotask(decrementExpectedAwaits);\n }\n };\n }\n function execInGlobalContext(cb) {\n if (Promise === NativePromise && task.echoes === 0) {\n if (zoneEchoes === 0) {\n cb();\n }\n else {\n enqueueNativeMicroTask(cb);\n }\n }\n else {\n setTimeout(cb, 0);\n }\n }\n var rejection = DexiePromise.reject;\n\n function tempTransaction(db, mode, storeNames, fn) {\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._state.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop);\n }\n return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); });\n }\n else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db.close({ disableAutoOpen: false });\n return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); });\n }\n return rejection(ex);\n }\n return trans._promise(mode, function (resolve, reject) {\n return newScope(function () {\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(function (result) {\n if (mode === 'readwrite')\n try {\n trans.idbtrans.commit();\n }\n catch (_a) { }\n return mode === 'readonly' ? result : trans._completion.then(function () { return result; });\n });\n }\n }\n\n var DEXIE_VERSION = '4.0.10';\n var maxString = String.fromCharCode(65535);\n var minKey = -Infinity;\n var INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\n var STRING_EXPECTED = \"String expected.\";\n var connections = [];\n var DBNAMES_DB = '__dbnames';\n var READONLY = 'readonly';\n var READWRITE = 'readwrite';\n\n function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n }\n\n var AnyRange = {\n type: 3 ,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n };\n\n function workaroundForUndefinedPrimKey(keyPath) {\n return typeof keyPath === \"string\" && !/\\./.test(keyPath)\n ? function (obj) {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : function (obj) { return obj; };\n }\n\n function Entity() {\n throw exceptions.Type();\n }\n\n function cmp(a, b) {\n try {\n var ta = type(a);\n var tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array')\n return 1;\n if (tb === 'Array')\n return -1;\n if (ta === 'binary')\n return 1;\n if (tb === 'binary')\n return -1;\n if (ta === 'string')\n return 1;\n if (tb === 'string')\n return -1;\n if (ta === 'Date')\n return 1;\n if (tb !== 'Date')\n return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n }\n catch (_a) { }\n return NaN;\n }\n function compareArrays(a, b) {\n var al = a.length;\n var bl = b.length;\n var l = al < bl ? al : bl;\n for (var i = 0; i < l; ++i) {\n var res = cmp(a[i], b[i]);\n if (res !== 0)\n return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n }\n function compareUint8Arrays(a, b) {\n var al = a.length;\n var bl = b.length;\n var l = al < bl ? al : bl;\n for (var i = 0; i < l; ++i) {\n if (a[i] !== b[i])\n return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n }\n function type(x) {\n var t = typeof x;\n if (t !== 'object')\n return t;\n if (ArrayBuffer.isView(x))\n return 'binary';\n var tsTag = toStringTag(x);\n return tsTag === 'ArrayBuffer' ? 'binary' : tsTag;\n }\n function getUint8Array(a) {\n if (a instanceof Uint8Array)\n return a;\n if (ArrayBuffer.isView(a))\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a);\n }\n\n var Table = (function () {\n function Table() {\n }\n Table.prototype._trans = function (mode, fn, writeLocked) {\n var trans = this._tx || PSD.trans;\n var tableName = this.name;\n var task = debug && typeof console !== 'undefined' && console.createTask && console.createTask(\"Dexie: \".concat(mode === 'readonly' ? 'read' : 'write', \" \").concat(this.name));\n function checkTableInTransaction(resolve, reject, trans) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n var wasRootExec = beginMicroTickScope();\n try {\n var p = trans && trans.db._novip === this.db._novip ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n if (task) {\n p._consoleTask = task;\n p = p.catch(function (err) {\n console.trace(err);\n return rejection(err);\n });\n }\n return p;\n }\n finally {\n if (wasRootExec)\n endMicroTickScope();\n }\n };\n Table.prototype.get = function (keyOrCrit, cb) {\n var _this = this;\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n if (keyOrCrit == null)\n return rejection(new exceptions.Type(\"Invalid argument to Table.get()\"));\n return this._trans('readonly', function (trans) {\n return _this.core.get({ trans: trans, key: keyOrCrit })\n .then(function (res) { return _this.hook.reading.fire(res); });\n }).then(cb);\n };\n Table.prototype.where = function (indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, \"[\".concat(indexOrCrit.join('+'), \"]\"));\n var keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) {\n if (ix.compound &&\n keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) {\n for (var i = 0; i < keyPaths.length; ++i) {\n if (keyPaths.indexOf(ix.keyPath[i]) === -1)\n return false;\n }\n return true;\n }\n return false;\n }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0];\n if (compoundIndex && this.db._maxKey !== maxString) {\n var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(function (kp) { return indexOrCrit[kp]; }));\n }\n if (!compoundIndex && debug)\n console.warn(\"The query \".concat(JSON.stringify(indexOrCrit), \" on \").concat(this.name, \" would benefit from a \") +\n \"compound index [\".concat(keyPaths.join('+'), \"]\"));\n var idxByName = this.schema.idxByName;\n function equals(a, b) {\n return cmp(a, b) === 0;\n }\n var _a = keyPaths.reduce(function (_a, keyPath) {\n var prevIndex = _a[0], prevFilterFn = _a[1];\n var index = idxByName[keyPath];\n var value = indexOrCrit[keyPath];\n return [\n prevIndex || index,\n prevIndex || !index ?\n combine(prevFilterFn, index && index.multi ?\n function (x) {\n var prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(function (item) { return equals(value, item); });\n } : function (x) { return equals(value, getByKeyPath(x, keyPath)); })\n : prevFilterFn\n ];\n }, [null, null]), idx = _a[0], filterFunction = _a[1];\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) :\n this.where(keyPaths).equals('');\n };\n Table.prototype.filter = function (filterFunction) {\n return this.toCollection().and(filterFunction);\n };\n Table.prototype.count = function (thenShortcut) {\n return this.toCollection().count(thenShortcut);\n };\n Table.prototype.offset = function (offset) {\n return this.toCollection().offset(offset);\n };\n Table.prototype.limit = function (numRows) {\n return this.toCollection().limit(numRows);\n };\n Table.prototype.each = function (callback) {\n return this.toCollection().each(callback);\n };\n Table.prototype.toArray = function (thenShortcut) {\n return this.toCollection().toArray(thenShortcut);\n };\n Table.prototype.toCollection = function () {\n return new this.db.Collection(new this.db.WhereClause(this));\n };\n Table.prototype.orderBy = function (index) {\n return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ?\n \"[\".concat(index.join('+'), \"]\") :\n index));\n };\n Table.prototype.reverse = function () {\n return this.toCollection().reverse();\n };\n Table.prototype.mapToClass = function (constructor) {\n var _a = this, db = _a.db, tableName = _a.name;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = (function (_super) {\n __extends(class_1, _super);\n function class_1() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(class_1.prototype, \"db\", {\n get: function () { return db; },\n enumerable: false,\n configurable: true\n });\n class_1.prototype.table = function () { return tableName; };\n return class_1;\n }(constructor));\n }\n var inheritedProps = new Set();\n for (var proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); });\n }\n var readHook = function (obj) {\n if (!obj)\n return obj;\n var res = Object.create(constructor.prototype);\n for (var m in obj)\n if (!inheritedProps.has(m))\n try {\n res[m] = obj[m];\n }\n catch (_) { }\n return res;\n };\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n };\n Table.prototype.defineClass = function () {\n function Class(content) {\n extend(this, content);\n }\n return this.mapToClass(Class);\n };\n Table.prototype.add = function (obj, key) {\n var _this = this;\n var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath;\n var objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', function (trans) {\n return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] });\n }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; })\n .then(function (lastResult) {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n };\n Table.prototype.update = function (keyOrObject, modifications) {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined)\n return rejection(new exceptions.InvalidArgument(\"Given object does not contain its primary key\"));\n return this.where(\":id\").equals(key).modify(modifications);\n }\n else {\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n };\n Table.prototype.put = function (obj, key) {\n var _this = this;\n var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath;\n var objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); })\n .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; })\n .then(function (lastResult) {\n if (keyPath) {\n try {\n setByKeyPath(obj, keyPath, lastResult);\n }\n catch (_) { }\n }\n return lastResult;\n });\n };\n Table.prototype.delete = function (key) {\n var _this = this;\n return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); })\n .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });\n };\n Table.prototype.clear = function () {\n var _this = this;\n return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); })\n .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });\n };\n Table.prototype.bulkGet = function (keys) {\n var _this = this;\n return this._trans('readonly', function (trans) {\n return _this.core.getMany({\n keys: keys,\n trans: trans\n }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); });\n });\n };\n Table.prototype.bulkAdd = function (objects, keysOrOptions, options) {\n var _this = this;\n var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n var wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', function (trans) {\n var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n var numObjects = objects.length;\n var objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, wantResults: wantResults })\n .then(function (_a) {\n var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures;\n var result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(\"\".concat(_this.name, \".bulkAdd(): \").concat(numFailures, \" of \").concat(numObjects, \" operations failed\"), failures);\n });\n });\n };\n Table.prototype.bulkPut = function (objects, keysOrOptions, options) {\n var _this = this;\n var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions);\n var wantResults = options ? options.allKeys : undefined;\n return this._trans('readwrite', function (trans) {\n var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n var numObjects = objects.length;\n var objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, wantResults: wantResults })\n .then(function (_a) {\n var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures;\n var result = wantResults ? results : lastResult;\n if (numFailures === 0)\n return result;\n throw new BulkError(\"\".concat(_this.name, \".bulkPut(): \").concat(numFailures, \" of \").concat(numObjects, \" operations failed\"), failures);\n });\n });\n };\n Table.prototype.bulkUpdate = function (keysAndChanges) {\n var _this = this;\n var coreTable = this.core;\n var keys = keysAndChanges.map(function (entry) { return entry.key; });\n var changeSpecs = keysAndChanges.map(function (entry) { return entry.changes; });\n var offsetMap = [];\n return this._trans('readwrite', function (trans) {\n return coreTable.getMany({ trans: trans, keys: keys, cache: 'clone' }).then(function (objs) {\n var resultKeys = [];\n var resultObjs = [];\n keysAndChanges.forEach(function (_a, idx) {\n var key = _a.key, changes = _a.changes;\n var obj = objs[idx];\n if (obj) {\n for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) {\n var keyPath = _b[_i];\n var value = changes[keyPath];\n if (keyPath === _this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\"Cannot update primary key in bulkUpdate()\");\n }\n }\n else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n var numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans: trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys: keys,\n changeSpecs: changeSpecs\n }\n })\n .then(function (_a) {\n var numFailures = _a.numFailures, failures = _a.failures;\n if (numFailures === 0)\n return numEntries;\n for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) {\n var offset = _b[_i];\n var mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n var failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\"\".concat(_this.name, \".bulkUpdate(): \").concat(numFailures, \" of \").concat(numEntries, \" operations failed\"), failures);\n });\n });\n });\n };\n Table.prototype.bulkDelete = function (keys) {\n var _this = this;\n var numKeys = keys.length;\n return this._trans('readwrite', function (trans) {\n return _this.core.mutate({ trans: trans, type: 'delete', keys: keys });\n }).then(function (_a) {\n var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures;\n if (numFailures === 0)\n return lastResult;\n throw new BulkError(\"\".concat(_this.name, \".bulkDelete(): \").concat(numFailures, \" of \").concat(numKeys, \" operations failed\"), failures);\n });\n };\n return Table;\n }());\n\n function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n var i = arguments.length, args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n }\n else if (typeof (eventName) === 'string') {\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n return rv;\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object')\n return addConfiguredEvents(eventName);\n if (!chainFunction)\n chainFunction = reverseStoppableEventChain;\n if (!defaultFunction)\n defaultFunction = nop;\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n function addConfiguredEvents(cfg) {\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n }\n else if (args === 'asap') {\n var context = add(eventName, mirror, function fire() {\n var i = arguments.length, args = new Array(i);\n while (i--)\n args[i] = arguments[i];\n context.subscribers.forEach(function (fn) {\n asap$1(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n }\n else\n throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n }\n\n function makeClassConstructor(prototype, constructor) {\n derive(constructor).from({ prototype: prototype });\n return constructor;\n }\n\n function createTableConstructor(db) {\n return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n });\n }\n\n function isPlainKeyRange(ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n }\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n function addReplayFilter(ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n function getIndexOrStore(ctx, coreSchema) {\n if (ctx.isPrimKey)\n return coreSchema.primaryKey;\n var index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index)\n throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n }\n function openCursor(ctx, coreTable, trans) {\n var index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans: trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index: index,\n range: ctx.range\n }\n });\n }\n function iter(ctx, fn, coreTrans, coreTable) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n }\n else {\n var set_1 = {};\n var union = function (item, cursor, advance) {\n if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]')\n key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set_1, key)) {\n set_1[key] = true;\n fn(item, cursor, advance);\n }\n }\n };\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n }\n function iterate(cursorPromise, filter, fn, valueMapper) {\n var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn;\n var wrappedFn = wrap(mappedFn);\n return cursorPromise.then(function (cursor) {\n if (cursor) {\n return cursor.start(function () {\n var c = function () { return cursor.continue(); };\n if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; }))\n wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; });\n c();\n });\n }\n });\n }\n\n var PropModSymbol = Symbol();\n var PropModification = (function () {\n function PropModification(spec) {\n Object.assign(this, spec);\n }\n PropModification.prototype.execute = function (value) {\n var _a;\n if (this.add !== undefined) {\n var term = this.add;\n if (isArray(term)) {\n return __spreadArray(__spreadArray([], (isArray(value) ? value : []), true), term, true).sort();\n }\n if (typeof term === 'number')\n return (Number(value) || 0) + term;\n if (typeof term === 'bigint') {\n try {\n return BigInt(value) + term;\n }\n catch (_b) {\n return BigInt(0) + term;\n }\n }\n throw new TypeError(\"Invalid term \".concat(term));\n }\n if (this.remove !== undefined) {\n var subtrahend_1 = this.remove;\n if (isArray(subtrahend_1)) {\n return isArray(value) ? value.filter(function (item) { return !subtrahend_1.includes(item); }).sort() : [];\n }\n if (typeof subtrahend_1 === 'number')\n return Number(value) - subtrahend_1;\n if (typeof subtrahend_1 === 'bigint') {\n try {\n return BigInt(value) - subtrahend_1;\n }\n catch (_c) {\n return BigInt(0) - subtrahend_1;\n }\n }\n throw new TypeError(\"Invalid subtrahend \".concat(subtrahend_1));\n }\n var prefixToReplace = (_a = this.replacePrefix) === null || _a === void 0 ? void 0 : _a[0];\n if (prefixToReplace && typeof value === 'string' && value.startsWith(prefixToReplace)) {\n return this.replacePrefix[1] + value.substring(prefixToReplace.length);\n }\n return value;\n };\n return PropModification;\n }());\n\n var Collection = (function () {\n function Collection() {\n }\n Collection.prototype._read = function (fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n };\n Collection.prototype._write = function (fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\");\n };\n Collection.prototype._addAlgorithm = function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n };\n Collection.prototype._iterate = function (fn, coreTrans) {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n };\n Collection.prototype.clone = function (props) {\n var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx);\n if (props)\n extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n };\n Collection.prototype.raw = function () {\n this._ctx.valueMapper = null;\n return this;\n };\n Collection.prototype.each = function (fn) {\n var ctx = this._ctx;\n return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); });\n };\n Collection.prototype.count = function (cb) {\n var _this = this;\n return this._read(function (trans) {\n var ctx = _this._ctx;\n var coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n return coreTable.count({\n trans: trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(function (count) { return Math.min(count, ctx.limit); });\n }\n else {\n var count = 0;\n return iter(ctx, function () { ++count; return false; }, trans, coreTable)\n .then(function () { return count; });\n }\n }).then(cb);\n };\n Collection.prototype.sortBy = function (keyPath, cb) {\n var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i)\n return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n function sorter(a, b) {\n var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex);\n return cmp(aVal, bVal) * order;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n };\n Collection.prototype.toArray = function (cb) {\n var _this = this;\n return this._read(function (trans) {\n var ctx = _this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n var valueMapper_1 = ctx.valueMapper;\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans: trans,\n limit: ctx.limit,\n values: true,\n query: {\n index: index,\n range: ctx.range\n }\n }).then(function (_a) {\n var result = _a.result;\n return valueMapper_1 ? result.map(valueMapper_1) : result;\n });\n }\n else {\n var a_1 = [];\n return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; });\n }\n }, cb);\n };\n Collection.prototype.offset = function (offset) {\n var ctx = this._ctx;\n if (offset <= 0)\n return this;\n ctx.offset += offset;\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function (cursor, advance) {\n if (offsetLeft === 0)\n return true;\n if (offsetLeft === 1) {\n --offsetLeft;\n return false;\n }\n advance(function () {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n }\n else {\n addReplayFilter(ctx, function () {\n var offsetLeft = offset;\n return function () { return (--offsetLeft < 0); };\n });\n }\n return this;\n };\n Collection.prototype.limit = function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows);\n addReplayFilter(this._ctx, function () {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0)\n advance(resolve);\n return rowsLeft >= 0;\n };\n }, true);\n return this;\n };\n Collection.prototype.until = function (filterFunction, bIncludeStopEntry) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n }\n else {\n return true;\n }\n });\n return this;\n };\n Collection.prototype.first = function (cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n };\n Collection.prototype.last = function (cb) {\n return this.reverse().first(cb);\n };\n Collection.prototype.filter = function (filterFunction) {\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n addMatchFilter(this._ctx, filterFunction);\n return this;\n };\n Collection.prototype.and = function (filter) {\n return this.filter(filter);\n };\n Collection.prototype.or = function (indexName) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n };\n Collection.prototype.reverse = function () {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange)\n this._ondirectionchange(this._ctx.dir);\n return this;\n };\n Collection.prototype.desc = function () {\n return this.reverse();\n };\n Collection.prototype.eachKey = function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n };\n Collection.prototype.eachUniqueKey = function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n };\n Collection.prototype.eachPrimaryKey = function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n };\n Collection.prototype.keys = function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n };\n Collection.prototype.primaryKeys = function (cb) {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n return this._read(function (trans) {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans: trans,\n values: false,\n limit: ctx.limit,\n query: {\n index: index,\n range: ctx.range\n }\n });\n }).then(function (_a) {\n var result = _a.result;\n return result;\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n };\n Collection.prototype.uniqueKeys = function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n };\n Collection.prototype.firstKey = function (cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n };\n Collection.prototype.lastKey = function (cb) {\n return this.reverse().firstKey(cb);\n };\n Collection.prototype.distinct = function () {\n var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi)\n return this;\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString();\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n };\n Collection.prototype.modify = function (changes) {\n var _this = this;\n var ctx = this._ctx;\n return this._write(function (trans) {\n var modifyer;\n if (typeof changes === 'function') {\n modifyer = changes;\n }\n else {\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i];\n var val = changes[keyPath];\n var origVal = getByKeyPath(item, keyPath);\n if (val instanceof PropModification) {\n setByKeyPath(item, keyPath, val.execute(origVal));\n anythingModified = true;\n }\n else if (origVal !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n var coreTable = ctx.table.core;\n var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey;\n var limit = 200;\n var modifyChunkSize = _this.db._options.modifyChunkSize;\n if (modifyChunkSize) {\n if (typeof modifyChunkSize == 'object') {\n limit = modifyChunkSize[coreTable.name] || modifyChunkSize['*'] || 200;\n }\n else {\n limit = modifyChunkSize;\n }\n }\n var totalFailures = [];\n var successCount = 0;\n var failedKeys = [];\n var applyMutateResult = function (expectedCount, res) {\n var failures = res.failures, numFailures = res.numFailures;\n successCount += expectedCount - numFailures;\n for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) {\n var pos = _a[_i];\n totalFailures.push(failures[pos]);\n }\n };\n return _this.clone().primaryKeys().then(function (keys) {\n var criteria = isPlainKeyRange(ctx) &&\n ctx.limit === Infinity &&\n (typeof changes !== 'function' || changes === deleteCallback) && {\n index: ctx.index,\n range: ctx.range\n };\n var nextChunk = function (offset) {\n var count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans: trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\"\n }).then(function (values) {\n var addValues = [];\n var putValues = [];\n var putKeys = outbound ? [] : null;\n var deleteKeys = [];\n for (var i = 0; i < count; ++i) {\n var origValue = values[i];\n var ctx_1 = {\n value: deepClone(origValue),\n primKey: keys[offset + i]\n };\n if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {\n if (ctx_1.value == null) {\n deleteKeys.push(keys[offset + i]);\n }\n else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {\n deleteKeys.push(keys[offset + i]);\n addValues.push(ctx_1.value);\n }\n else {\n putValues.push(ctx_1.value);\n if (outbound)\n putKeys.push(keys[offset + i]);\n }\n }\n }\n return Promise.resolve(addValues.length > 0 &&\n coreTable.mutate({ trans: trans, type: 'add', values: addValues })\n .then(function (res) {\n for (var pos in res.failures) {\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })).then(function () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans: trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria: criteria,\n changeSpec: typeof changes !== 'function'\n && changes,\n isAdditionalChunk: offset > 0\n }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans: trans,\n type: 'delete',\n keys: deleteKeys,\n criteria: criteria,\n isAdditionalChunk: offset > 0\n }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n };\n return nextChunk(0).then(function () {\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys);\n return keys.length;\n });\n });\n });\n };\n Collection.prototype.delete = function () {\n var ctx = this._ctx, range = ctx.range;\n if (isPlainKeyRange(ctx) &&\n (ctx.isPrimKey || range.type === 3 ))\n {\n return this._write(function (trans) {\n var primaryKey = ctx.table.core.schema.primaryKey;\n var coreRange = range;\n return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) {\n return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange })\n .then(function (_a) {\n var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures;\n if (numFailures)\n throw new ModifyError(\"Could not delete some values\", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n return this.modify(deleteCallback);\n };\n return Collection;\n }());\n var deleteCallback = function (value, ctx) { return ctx.value = null; };\n\n function createCollectionConstructor(db) {\n return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) {\n this.db = db;\n var keyRange = AnyRange, error = null;\n if (keyRangeGenerator)\n try {\n keyRange = keyRangeGenerator();\n }\n catch (ex) {\n error = ex;\n }\n var whereCtx = whereClause._ctx;\n var table = whereCtx.table;\n var readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true,\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error,\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n });\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection(collectionOrWhereClause) :\n collectionOrWhereClause;\n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n function emptyCollection(whereClause) {\n return new whereClause.Collection(whereClause, function () { return rangeEqual(\"\"); }).limit(0);\n }\n function upperFactory(dir) {\n return dir === \"next\" ?\n function (s) { return s.toUpperCase(); } :\n function (s) { return s.toLowerCase(); };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ?\n function (s) { return s.toLowerCase(); } :\n function (s) { return s.toUpperCase(); };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0)\n return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0)\n return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0)\n return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0)\n llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\")\n return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\")\n return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n }\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length;\n if (!needles.every(function (s) { return typeof s === 'string'; })) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle) {\n return { lower: lower(needle), upper: upper(needle) };\n }).sort(function (a, b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb) { return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb) { return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n var c = new whereClause.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); });\n c._ondirectionchange = function (direction) {\n initDirection(direction);\n };\n var firstPossibleNeedle = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n if (typeof key !== 'string')\n return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n }\n else {\n var lowestPossibleCasing = null;\n for (var i = firstPossibleNeedle; i < needlesLen; ++i) {\n var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);\n if (casing === null && lowestPossibleCasing === null)\n firstPossibleNeedle = i + 1;\n else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n }\n else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n function createRange(lower, upper, lowerOpen, upperOpen) {\n return {\n type: 2 ,\n lower: lower,\n upper: upper,\n lowerOpen: lowerOpen,\n upperOpen: upperOpen\n };\n }\n function rangeEqual(value) {\n return {\n type: 1 ,\n lower: value,\n upper: value\n };\n }\n\n var WhereClause = (function () {\n function WhereClause() {\n }\n Object.defineProperty(WhereClause.prototype, \"Collection\", {\n get: function () {\n return this._ctx.table.db.Collection;\n },\n enumerable: false,\n configurable: true\n });\n WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) {\n includeLower = includeLower !== false;\n includeUpper = includeUpper === true;\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this);\n return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); });\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n };\n WhereClause.prototype.equals = function (value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, function () { return rangeEqual(value); });\n };\n WhereClause.prototype.above = function (value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, function () { return createRange(value, undefined, true); });\n };\n WhereClause.prototype.aboveOrEqual = function (value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, function () { return createRange(value, undefined, false); });\n };\n WhereClause.prototype.below = function (value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, function () { return createRange(undefined, value, false, true); });\n };\n WhereClause.prototype.belowOrEqual = function (value) {\n if (value == null)\n return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, function () { return createRange(undefined, value); });\n };\n WhereClause.prototype.startsWith = function (str) {\n if (typeof str !== 'string')\n return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n };\n WhereClause.prototype.startsWithIgnoreCase = function (str) {\n if (str === \"\")\n return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\n };\n WhereClause.prototype.equalsIgnoreCase = function (str) {\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\n };\n WhereClause.prototype.anyOfIgnoreCase = function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\n };\n WhereClause.prototype.startsWithAnyOfIgnoreCase = function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function (n) { return x.indexOf(n) === 0; }); }, set, maxString);\n };\n WhereClause.prototype.anyOf = function () {\n var _this = this;\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = this._cmp;\n try {\n set.sort(compare);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n if (set.length === 0)\n return emptyCollection(this);\n var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); });\n c._ondirectionchange = function (direction) {\n compare = (direction === \"next\" ?\n _this._ascending :\n _this._descending);\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n ++i;\n if (i === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n return true;\n }\n else {\n advance(function () { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n };\n WhereClause.prototype.notEqual = function (value) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n };\n WhereClause.prototype.noneOf = function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0)\n return new this.Collection(this);\n try {\n set.sort(this._ascending);\n }\n catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n var ranges = set.reduce(function (res, val) { return res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]]; }, null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n };\n WhereClause.prototype.inAnyRange = function (ranges, options) {\n var _this = this;\n var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max;\n if (ranges.length === 0)\n return emptyCollection(this);\n if (!ranges.every(function (range) {\n return range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0;\n })) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false;\n var includeUppers = options && options.includeUppers === true;\n function addRange(ranges, newRange) {\n var i = 0, l = ranges.length;\n for (; i < l; ++i) {\n var range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n var sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n }\n catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n var rangePos = 0;\n var keyIsBeyondCurrentEntry = includeUppers ?\n function (key) { return ascending(key, set[rangePos][1]) > 0; } :\n function (key) { return ascending(key, set[rangePos][1]) >= 0; };\n var keyIsBeforeCurrentEntry = includeLowers ?\n function (key) { return descending(key, set[rangePos][0]) > 0; } :\n function (key) { return descending(key, set[rangePos][0]) >= 0; };\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n var checkKey = keyIsBeyondCurrentEntry;\n var c = new this.Collection(this, function () { return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); });\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n }\n else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n ++rangePos;\n if (rangePos === set.length) {\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n return true;\n }\n else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) {\n return false;\n }\n else {\n advance(function () {\n if (sortDirection === ascending)\n cursor.continue(set[rangePos][0]);\n else\n cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n };\n WhereClause.prototype.startsWithAnyOf = function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (!set.every(function (s) { return typeof s === 'string'; })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0)\n return emptyCollection(this);\n return this.inAnyRange(set.map(function (str) { return [str, str + maxString]; }));\n };\n return WhereClause;\n }());\n\n function createWhereClauseConstructor(db) {\n return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n this._cmp = this._ascending = cmp;\n this._descending = function (a, b) { return cmp(b, a); };\n this._max = function (a, b) { return cmp(a, b) > 0 ? a : b; };\n this._min = function (a, b) { return cmp(a, b) < 0 ? a : b; };\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange)\n throw new exceptions.MissingAPI();\n });\n }\n\n function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject(event.target.error);\n return false;\n });\n }\n function preventDefault(event) {\n if (event.stopPropagation)\n event.stopPropagation();\n if (event.preventDefault)\n event.preventDefault();\n }\n\n var DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated';\n var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME);\n\n var Transaction = (function () {\n function Transaction() {\n }\n Transaction.prototype._lock = function () {\n assert(!PSD.global);\n ++this._reculock;\n if (this._reculock === 1 && !PSD.global)\n PSD.lockOwnerFor = this;\n return this;\n };\n Transaction.prototype._unlock = function () {\n assert(!PSD.global);\n if (--this._reculock === 0) {\n if (!PSD.global)\n PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try {\n usePSD(fnAndPSD[1], fnAndPSD[0]);\n }\n catch (e) { }\n }\n }\n return this;\n };\n Transaction.prototype._locked = function () {\n return this._reculock && PSD.lockOwnerFor !== this;\n };\n Transaction.prototype.create = function (idbtrans) {\n var _this = this;\n if (!this.mode)\n return this;\n var idbdb = this.db.idbdb;\n var dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active)\n throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core\n ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }));\n idbtrans.onerror = wrap(function (ev) {\n preventDefault(ev);\n _this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(function (ev) {\n preventDefault(ev);\n _this.active && _this._reject(new exceptions.Abort(idbtrans.error));\n _this.active = false;\n _this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(function () {\n _this.active = false;\n _this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n };\n Transaction.prototype._promise = function (mode, fn, bWriteLock) {\n var _this = this;\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n if (this._locked()) {\n return new DexiePromise(function (resolve, reject) {\n _this._blockedFuncs.push([function () {\n _this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n }\n else if (bWriteLock) {\n return newScope(function () {\n var p = new DexiePromise(function (resolve, reject) {\n _this._lock();\n var rv = fn(resolve, reject, _this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p.finally(function () { return _this._unlock(); });\n p._lib = true;\n return p;\n });\n }\n else {\n var p = new DexiePromise(function (resolve, reject) {\n var rv = fn(resolve, reject, _this);\n if (rv && rv.then)\n rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n };\n Transaction.prototype._root = function () {\n return this.parent ? this.parent._root() : this;\n };\n Transaction.prototype.waitFor = function (promiseLike) {\n var root = this._root();\n var promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n root._waitingFor = root._waitingFor.then(function () { return promise; });\n }\n else {\n root._waitingFor = promise;\n root._waitingQueue = [];\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount;\n while (root._waitingQueue.length)\n (root._waitingQueue.shift())();\n if (root._waitingFor)\n store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise(function (resolve, reject) {\n promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () {\n if (root._waitingFor === currentWaitPromise) {\n root._waitingFor = null;\n }\n });\n });\n };\n Transaction.prototype.abort = function () {\n if (this.active) {\n this.active = false;\n if (this.idbtrans)\n this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n };\n Transaction.prototype.table = function (tableName) {\n var memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n var tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n }\n var transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n };\n return Transaction;\n }());\n\n function createTransactionConstructor(db) {\n return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {\n var _this = this;\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0;\n this._completion = new DexiePromise(function (resolve, reject) {\n _this._resolve = resolve;\n _this._reject = reject;\n });\n this._completion.then(function () {\n _this.active = false;\n _this.on.complete.fire();\n }, function (e) {\n var wasActive = _this.active;\n _this.active = false;\n _this.on.error.fire(e);\n _this.parent ?\n _this.parent._reject(e) :\n wasActive && _this.idbtrans && _this.idbtrans.abort();\n return rejection(e);\n });\n });\n }\n\n function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {\n return {\n name: name,\n keyPath: keyPath,\n unique: unique,\n multi: multi,\n auto: auto,\n compound: compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n };\n }\n function nameFromKeyPath(keyPath) {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n }\n\n function createTableSchema(name, primKey, indexes) {\n return {\n name: name,\n primKey: primKey,\n indexes: indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; })\n };\n }\n\n function safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n }\n var getMaxKey = function (IdbKeyRange) {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = function () { return [[]]; };\n return [[]];\n }\n catch (e) {\n getMaxKey = function () { return maxString; };\n return maxString;\n }\n };\n\n function getKeyExtractor(keyPath) {\n if (keyPath == null) {\n return function () { return undefined; };\n }\n else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n }\n else {\n return function (obj) { return getByKeyPath(obj, keyPath); };\n }\n }\n function getSinglePathKeyExtractor(keyPath) {\n var split = keyPath.split('.');\n if (split.length === 1) {\n return function (obj) { return obj[keyPath]; };\n }\n else {\n return function (obj) { return getByKeyPath(obj, keyPath); };\n }\n }\n\n function arrayify(arrayLike) {\n return [].slice.call(arrayLike);\n }\n var _id_counter = 0;\n function getKeyPathAlias(keyPath) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n \"[\".concat(keyPath.join('+'), \"]\");\n }\n function createDBCore(db, IdbKeyRange, tmpTrans) {\n function extractSchema(db, trans) {\n var tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) {\n var keyPath = store.keyPath, autoIncrement = store.autoIncrement;\n var compound = isArray(keyPath);\n var outbound = keyPath == null;\n var indexByKeyPath = {};\n var result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound: outbound,\n compound: compound,\n keyPath: keyPath,\n autoIncrement: autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n },\n indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); })\n .map(function (index) {\n var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath;\n var compound = isArray(keyPath);\n var result = {\n name: name,\n compound: compound,\n keyPath: keyPath,\n unique: unique,\n multiEntry: multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; }\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n };\n }\n function makeIDBKeyRange(range) {\n if (range.type === 3 )\n return null;\n if (range.type === 4 )\n throw new Error(\"Cannot convert never type to IDBKeyRange\");\n var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen;\n var idbRange = lower === undefined ?\n upper === undefined ?\n null :\n IdbKeyRange.upperBound(upper, !!upperOpen) :\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) :\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n function createDbCoreTable(tableSchema) {\n var tableName = tableSchema.name;\n function mutate(_a) {\n var trans = _a.trans, type = _a.type, keys = _a.keys, values = _a.values, range = _a.range;\n return new Promise(function (resolve, reject) {\n resolve = wrap(resolve);\n var store = trans.objectStore(tableName);\n var outbound = store.keyPath == null;\n var isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error(\"Invalid operation type: \" + type);\n var length = (keys || values || { length: 1 }).length;\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined });\n var req;\n var reqs = [];\n var failures = [];\n var numFailures = 0;\n var errorHandler = function (event) {\n ++numFailures;\n preventDefault(event);\n };\n if (type === 'deleteRange') {\n if (range.type === 4 )\n return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined });\n if (range.type === 3 )\n reqs.push(req = store.clear());\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n }\n else {\n var _a = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null], args1 = _a[0], args2 = _a[1];\n if (isAddOrPut) {\n for (var i = 0; i < length; ++i) {\n reqs.push(req = (args2 && args2[i] !== undefined ?\n store[type](args1[i], args2[i]) :\n store[type](args1[i])));\n req.onerror = errorHandler;\n }\n }\n else {\n for (var i = 0; i < length; ++i) {\n reqs.push(req = store[type](args1[i]));\n req.onerror = errorHandler;\n }\n }\n }\n var done = function (event) {\n var lastResult = event.target.result;\n reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); });\n resolve({\n numFailures: numFailures,\n failures: failures,\n results: type === \"delete\" ? keys : reqs.map(function (req) { return req.result; }),\n lastResult: lastResult\n });\n };\n req.onerror = function (event) {\n errorHandler(event);\n done(event);\n };\n req.onsuccess = done;\n });\n }\n function openCursor(_a) {\n var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique;\n return new Promise(function (resolve, reject) {\n resolve = wrap(resolve);\n var index = query.index, range = query.range;\n var store = trans.objectStore(tableName);\n var source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n var direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n var req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function (ev) {\n var cursor = req.result;\n if (!cursor) {\n resolve(null);\n return;\n }\n cursor.___id = ++_id_counter;\n cursor.done = false;\n var _cursorContinue = cursor.continue.bind(cursor);\n var _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey)\n _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n var _cursorAdvance = cursor.advance.bind(cursor);\n var doThrowCursorIsNotStarted = function () { throw new Error(\"Cursor not started\"); };\n var doThrowCursorIsStopped = function () { throw new Error(\"Cursor not stopped\"); };\n cursor.trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function () {\n var _this = this;\n var gotOne = 1;\n return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; });\n };\n cursor.start = function (callback) {\n var iterationPromise = new Promise(function (resolveIteration, rejectIteration) {\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = function (value) {\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n var guardedCallback = function () {\n if (req.result) {\n try {\n callback();\n }\n catch (err) {\n cursor.fail(err);\n }\n }\n else {\n cursor.done = true;\n cursor.start = function () { throw new Error(\"Cursor behind last entry\"); };\n cursor.stop();\n }\n };\n req.onsuccess = wrap(function (ev) {\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject);\n });\n }\n function query(hasGetAll) {\n return function (request) {\n return new Promise(function (resolve, reject) {\n resolve = wrap(resolve);\n var trans = request.trans, values = request.values, limit = request.limit, query = request.query;\n var nonInfinitLimit = limit === Infinity ? undefined : limit;\n var index = query.index, range = query.range;\n var store = trans.objectStore(tableName);\n var source = index.isPrimaryKey ? store : store.index(index.name);\n var idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0)\n return resolve({ result: [] });\n if (hasGetAll) {\n var req = values ?\n source.getAll(idbKeyRange, nonInfinitLimit) :\n source.getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = function (event) { return resolve({ result: event.target.result }); };\n req.onerror = eventRejectHandler(reject);\n }\n else {\n var count_1 = 0;\n var req_1 = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange);\n var result_1 = [];\n req_1.onsuccess = function (event) {\n var cursor = req_1.result;\n if (!cursor)\n return resolve({ result: result_1 });\n result_1.push(values ? cursor.value : cursor.primaryKey);\n if (++count_1 === limit)\n return resolve({ result: result_1 });\n cursor.continue();\n };\n req_1.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n return {\n name: tableName,\n schema: tableSchema,\n mutate: mutate,\n getMany: function (_a) {\n var trans = _a.trans, keys = _a.keys;\n return new Promise(function (resolve, reject) {\n resolve = wrap(resolve);\n var store = trans.objectStore(tableName);\n var length = keys.length;\n var result = new Array(length);\n var keyCount = 0;\n var callbackCount = 0;\n var req;\n var successHandler = function (event) {\n var req = event.target;\n if ((result[req._pos] = req.result) != null)\n ;\n if (++callbackCount === keyCount)\n resolve(result);\n };\n var errorHandler = eventRejectHandler(reject);\n for (var i = 0; i < length; ++i) {\n var key = keys[i];\n if (key != null) {\n req = store.get(keys[i]);\n req._pos = i;\n req.onsuccess = successHandler;\n req.onerror = errorHandler;\n ++keyCount;\n }\n }\n if (keyCount === 0)\n resolve(result);\n });\n },\n get: function (_a) {\n var trans = _a.trans, key = _a.key;\n return new Promise(function (resolve, reject) {\n resolve = wrap(resolve);\n var store = trans.objectStore(tableName);\n var req = store.get(key);\n req.onsuccess = function (event) { return resolve(event.target.result); };\n req.onerror = eventRejectHandler(reject);\n });\n },\n query: query(hasGetAll),\n openCursor: openCursor,\n count: function (_a) {\n var query = _a.query, trans = _a.trans;\n var index = query.index, range = query.range;\n return new Promise(function (resolve, reject) {\n var store = trans.objectStore(tableName);\n var source = index.isPrimaryKey ? store : store.index(index.name);\n var idbKeyRange = makeIDBKeyRange(range);\n var req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); });\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll;\n var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); });\n var tableMap = {};\n tables.forEach(function (table) { return tableMap[table.name] = table; });\n return {\n stack: \"dbcore\",\n transaction: db.transaction.bind(db),\n table: function (name) {\n var result = tableMap[name];\n if (!result)\n throw new Error(\"Table '\".concat(name, \"' not found\"));\n return tableMap[name];\n },\n MIN_KEY: -Infinity,\n MAX_KEY: getMaxKey(IdbKeyRange),\n schema: schema\n };\n }\n\n function createMiddlewareStack(stackImpl, middlewares) {\n return middlewares.reduce(function (down, _a) {\n var create = _a.create;\n return (__assign(__assign({}, down), create(down)));\n }, stackImpl);\n }\n function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) {\n var IDBKeyRange = _a.IDBKeyRange; _a.indexedDB;\n var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore);\n return {\n dbcore: dbcore\n };\n }\n function generateMiddlewareStacks(db, tmpTrans) {\n var idbdb = tmpTrans.db;\n var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore;\n db.tables.forEach(function (table) {\n var tableName = table.name;\n if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n }\n\n function setApiOnPlace(db, objs, tableNames, dbschema) {\n tableNames.forEach(function (tableName) {\n var schema = dbschema[tableName];\n objs.forEach(function (obj) {\n var propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n setProp(obj, tableName, {\n get: function () { return this.table(tableName); },\n set: function (value) {\n defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true });\n }\n });\n }\n else {\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n }\n function removeTablesApi(db, objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof db.Table)\n delete obj[key];\n }\n });\n }\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) {\n var globalSchema = db._dbSchema;\n if (idbUpgradeTrans.objectStoreNames.contains('$meta') && !globalSchema.$meta) {\n globalSchema.$meta = createTableSchema(\"$meta\", parseIndexSyntax(\"\")[0], []);\n db._storeNames.push('$meta');\n }\n var trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n var transless = PSD.transless || PSD;\n newScope(function () {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction);\n }\n else {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n return getExistingVersion(db, trans, oldVersion)\n .then(function (oldVersion) { return updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans); })\n .catch(rejectTransaction);\n }\n });\n }\n function patchCurrentVersion(db, idbUpgradeTrans) {\n createMissingTables(db._dbSchema, idbUpgradeTrans);\n if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) {\n idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version');\n }\n var globalSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n adjustToExistingIndexNames(db, db._dbSchema, idbUpgradeTrans);\n var diff = getSchemaDiff(globalSchema, db._dbSchema);\n var _loop_1 = function (tableChange) {\n if (tableChange.change.length || tableChange.recreate) {\n console.warn(\"Unable to patch indexes of table \".concat(tableChange.name, \" because it has changes on the type of index or primary key.\"));\n return { value: void 0 };\n }\n var store = idbUpgradeTrans.objectStore(tableChange.name);\n tableChange.add.forEach(function (idx) {\n if (debug)\n console.debug(\"Dexie upgrade patch: Creating missing index \".concat(tableChange.name, \".\").concat(idx.src));\n addIndex(store, idx);\n });\n };\n for (var _i = 0, _a = diff.change; _i < _a.length; _i++) {\n var tableChange = _a[_i];\n var state_1 = _loop_1(tableChange);\n if (typeof state_1 === \"object\")\n return state_1.value;\n }\n }\n function getExistingVersion(db, trans, oldVersion) {\n if (trans.storeNames.includes('$meta')) {\n return trans.table('$meta').get('version').then(function (metaVersion) {\n return metaVersion != null ? metaVersion : oldVersion;\n });\n }\n else {\n return DexiePromise.resolve(oldVersion);\n }\n }\n function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) {\n var queue = [];\n var versions = db._versions;\n var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n var versToRun = versions.filter(function (v) { return v._cfg.version >= oldVersion; });\n if (versToRun.length === 0) {\n return DexiePromise.resolve();\n }\n versToRun.forEach(function (version) {\n queue.push(function () {\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema);\n diff.add.forEach(function (tuple) {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n }\n else {\n var store_1 = idbUpgradeTrans.objectStore(change.name);\n change.add.forEach(function (idx) { return addIndex(store_1, idx); });\n change.change.forEach(function (idx) {\n store_1.deleteIndex(idx.name);\n addIndex(store_1, idx);\n });\n change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); });\n }\n });\n var contentUpgrade = version._cfg.contentUpgrade;\n if (contentUpgrade && version._cfg.version > oldVersion) {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {};\n var upgradeSchema_1 = shallowClone(newSchema);\n diff.del.forEach(function (table) {\n upgradeSchema_1[table] = oldSchema[table];\n });\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1);\n trans.schema = upgradeSchema_1;\n var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync_1) {\n incrementExpectedAwaits();\n }\n var returnValue_1;\n var promiseFollowed = DexiePromise.follow(function () {\n returnValue_1 = contentUpgrade(trans);\n if (returnValue_1) {\n if (contentUpgradeIsAsync_1) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue_1.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue_1 && typeof returnValue_1.then === 'function' ?\n DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; }));\n }\n });\n queue.push(function (idbtrans) {\n var newSchema = version._cfg.dbschema;\n deleteRemovedTables(newSchema, idbtrans);\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n queue.push(function (idbtrans) {\n if (db.idbdb.objectStoreNames.contains('$meta')) {\n if (Math.ceil(db.idbdb.version / 10) === version._cfg.version) {\n db.idbdb.deleteObjectStore('$meta');\n delete db._dbSchema.$meta;\n db._storeNames = db._storeNames.filter(function (name) { return name !== '$meta'; });\n }\n else {\n idbtrans.objectStore('$meta').put(version._cfg.version, 'version');\n }\n }\n });\n });\n function runQueue() {\n return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n DexiePromise.resolve();\n }\n return runQueue().then(function () {\n createMissingTables(globalSchema, idbUpgradeTrans);\n });\n }\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [],\n add: [],\n change: []\n };\n var table;\n for (table in oldSchema) {\n if (!newSchema[table])\n diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table], newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n }\n else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if ((\n '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) ||\n (oldDef.primKey.auto !== newDef.primKey.auto)) {\n change.recreate = true;\n diff.change.push(change);\n }\n else {\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n var idxName = void 0;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName])\n change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName];\n if (!oldIdx)\n change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src)\n change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n function createTable(idbtrans, tableName, primKey, indexes) {\n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) { return addIndex(store, idx); });\n return store;\n }\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n if (debug)\n console.debug('Dexie: Creating missing table', tableName);\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n function deleteRemovedTables(newSchema, idbtrans) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) {\n return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName);\n });\n }\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n function buildGlobalSchema(db, idbdb, tmpTrans) {\n var globalSchema = {};\n var dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(function (storeName) {\n var store = tmpTrans.objectStore(storeName);\n var keyPath = store.keyPath;\n var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || \"\", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== \"string\", true);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== \"string\", false);\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n }\n function readGlobalSchema(db, idbdb, tmpTrans) {\n db.verno = idbdb.version / 10;\n var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n }\n function verifyInstalledSchema(db, tmpTrans) {\n var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n var diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; }));\n }\n function adjustToExistingIndexNames(db, schema, idbtrans) {\n var storeNames = idbtrans.db.objectStoreNames;\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) {\n db._hasGetAll = false;\n }\n }\n function parseIndexSyntax(primKeyAndIndexes) {\n return primKeyAndIndexes.split(',').map(function (index, indexNum) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\");\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n return createIndexSpec(name, keyPath || null, /\\&/.test(index), /\\*/.test(index), /\\+\\+/.test(index), isArray(keyPath), indexNum === 0);\n });\n }\n\n var Version = (function () {\n function Version() {\n }\n Version.prototype._parseStoresSpec = function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n primKey.unique = true;\n if (primKey.multi)\n throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(function (idx) {\n if (idx.auto)\n throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath)\n throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n };\n Version.prototype.stores = function (stores) {\n var db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n var versions = db._versions;\n var storesSpec = {};\n var dbschema = {};\n versions.forEach(function (version) {\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n db._dbSchema = dbschema;\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n };\n Version.prototype.upgrade = function (upgradeFunction) {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n };\n return Version;\n }());\n\n function createVersionConstructor(db) {\n return makeClassConstructor(Version.prototype, function Version(versionNumber) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n }\n\n function getDbNamesTable(indexedDB, IDBKeyRange) {\n var dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie$1(DBNAMES_DB, {\n addons: [],\n indexedDB: indexedDB,\n IDBKeyRange: IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\");\n }\n function hasDatabasesNative(indexedDB) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n }\n function getDatabaseNames(_a) {\n var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange;\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then(function (infos) {\n return infos\n .map(function (info) { return info.name; })\n .filter(function (name) { return name !== DBNAMES_DB; });\n })\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n }\n function _onDatabaseCreated(_a, name) {\n var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange;\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop);\n }\n function _onDatabaseDeleted(_a, name) {\n var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange;\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n }\n\n function vip(fn) {\n return newScope(function () {\n PSD.letThrough = true;\n return fn();\n });\n }\n\n function idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n }\n\n var _a;\n function isEmptyRange(node) {\n return !(\"from\" in node);\n }\n var RangeSet = function (fromOrTree, to) {\n if (this) {\n extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 });\n }\n else {\n var rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n };\n props(RangeSet.prototype, (_a = {\n add: function (rangeSet) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey: function (key) {\n addRange(this, key, key);\n return this;\n },\n addKeys: function (keys) {\n var _this = this;\n keys.forEach(function (key) { return addRange(_this, key, key); });\n return this;\n },\n hasKey: function (key) {\n var node = getRangeSetIterator(this).next(key).value;\n return node && cmp(node.from, key) <= 0 && cmp(node.to, key) >= 0;\n }\n },\n _a[iteratorSymbol] = function () {\n return getRangeSetIterator(this);\n },\n _a));\n function addRange(target, from, to) {\n var diff = cmp(from, to);\n if (isNaN(diff))\n return;\n if (diff > 0)\n throw RangeError();\n if (isEmptyRange(target))\n return extend(target, { from: from, to: to, d: 1 });\n var left = target.l;\n var right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from: from, to: to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from: from, to: to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null;\n target.d = right ? right.d + 1 : 1;\n }\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null;\n target.d = target.l ? target.l.d + 1 : 1;\n }\n var rightWasCutOff = !target.r;\n if (left && !target.l) {\n mergeRanges(target, left);\n }\n if (right && rightWasCutOff) {\n mergeRanges(target, right);\n }\n }\n function mergeRanges(target, newSet) {\n function _addRangeSet(target, _a) {\n var from = _a.from, to = _a.to, l = _a.l, r = _a.r;\n addRange(target, from, to);\n if (l)\n _addRangeSet(target, l);\n if (r)\n _addRangeSet(target, r);\n }\n if (!isEmptyRange(newSet))\n _addRangeSet(target, newSet);\n }\n function rangesOverlap(rangeSet1, rangeSet2) {\n var i1 = getRangeSetIterator(rangeSet2);\n var nextResult1 = i1.next();\n if (nextResult1.done)\n return false;\n var a = nextResult1.value;\n var i2 = getRangeSetIterator(rangeSet1);\n var nextResult2 = i2.next(a.from);\n var b = nextResult2.value;\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0)\n return true;\n cmp(a.from, b.from) < 0\n ? (a = (nextResult1 = i1.next(b.from)).value)\n : (b = (nextResult2 = i2.next(a.from)).value);\n }\n return false;\n }\n function getRangeSetIterator(node) {\n var state = isEmptyRange(node) ? null : { s: 0, n: node };\n return {\n next: function (key) {\n var keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n }\n else {\n while (state.n.l)\n state = { up: state, n: state.n.l, s: 1 };\n }\n case 1:\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n if (state.n.r) {\n state.s = 3;\n state = { up: state, n: state.n.r, s: 0 };\n continue;\n }\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n };\n }\n function rebalance(target) {\n var _a, _b;\n var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0);\n var r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n var l = r === \"r\" ? \"l\" : \"r\";\n var rootClone = __assign({}, target);\n var oldRootRight = target[r];\n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n }\n function computeDepth(_a) {\n var r = _a.r, l = _a.l;\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n }\n\n function extendObservabilitySet(target, newSet) {\n keys(newSet).forEach(function (part) {\n if (target[part])\n mergeRanges(target[part], newSet[part]);\n else\n target[part] = cloneSimpleObjectTree(newSet[part]);\n });\n return target;\n }\n\n function obsSetsOverlap(os1, os2) {\n return os1.all || os2.all || Object.keys(os1).some(function (key) { return os2[key] && rangesOverlap(os2[key], os1[key]); });\n }\n\n var cache = {};\n\n var unsignaledParts = {};\n var isTaskEnqueued = false;\n function signalSubscribersLazily(part, optimistic) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(function () {\n isTaskEnqueued = false;\n var parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts, false);\n }, 0);\n }\n }\n function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) {\n if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; }\n var queriesToSignal = new Set();\n if (updatedParts.all) {\n for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) {\n var tblCache = _a[_i];\n collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);\n }\n }\n else {\n for (var key in updatedParts) {\n var parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n var dbName = parts[1], tableName = parts[2];\n var tblCache = cache[\"idb://\".concat(dbName, \"/\").concat(tableName)];\n if (tblCache)\n collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);\n }\n }\n }\n queriesToSignal.forEach(function (requery) { return requery(); });\n }\n function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) {\n var updatedEntryLists = [];\n for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) {\n var _b = _a[_i], indexName = _b[0], entries = _b[1];\n var filteredEntries = [];\n for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) {\n var entry = entries_1[_c];\n if (obsSetsOverlap(updatedParts, entry.obsSet)) {\n entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });\n }\n else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) {\n var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1];\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n }\n\n function dexieOpen(db) {\n var state = db._state;\n var indexedDB = db._deps.indexedDB;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(function () { return state.dbOpenError ?\n rejection(state.dbOpenError) :\n db; });\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n var openCanceller = state.openCanceller;\n var nativeVerToOpen = Math.round(db.verno * 10);\n var schemaPatchMode = false;\n function throwIfCancelled() {\n if (state.openCanceller !== openCanceller)\n throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n var resolveDbReady = state.dbReadyResolve,\n upgradeTransaction = null, wasCreated = false;\n var tryOpenDB = function () { return new DexiePromise(function (resolve, reject) {\n throwIfCancelled();\n if (!indexedDB)\n throw new exceptions.MissingAPI();\n var dbName = db.name;\n var req = state.autoSchema || !nativeVerToOpen ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, nativeVerToOpen);\n if (!req)\n throw new exceptions.MissingAPI();\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap(function (e) {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) {\n req.onerror = preventDefault;\n upgradeTransaction.abort();\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName);\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject(new exceptions.NoSuchDatabase(\"Database \".concat(dbName, \" doesnt exist\")));\n });\n }\n else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion;\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n if (schemaPatchMode) {\n patchCurrentVersion(db, upgradeTransaction);\n }\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n req.onsuccess = wrap(function () {\n upgradeTransaction = null;\n var idbdb = db.idbdb = req.result;\n var objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0)\n try {\n var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema)\n readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans) && !schemaPatchMode) {\n console.warn(\"Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this.\");\n idbdb.close();\n nativeVerToOpen = idbdb.version + 1;\n schemaPatchMode = true;\n return resolve(tryOpenDB());\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n }\n catch (e) {\n }\n connections.push(db);\n idbdb.onversionchange = wrap(function (ev) {\n state.vcFired = true;\n db.on(\"versionchange\").fire(ev);\n });\n idbdb.onclose = wrap(function (ev) {\n db.on(\"close\").fire(ev);\n });\n if (wasCreated)\n _onDatabaseCreated(db._deps, dbName);\n resolve();\n }, reject);\n }).catch(function (err) {\n switch (err === null || err === void 0 ? void 0 : err.name) {\n case \"UnknownError\":\n if (state.PR1398_maxLoop > 0) {\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n }\n break;\n case \"VersionError\":\n if (nativeVerToOpen > 0) {\n nativeVerToOpen = 0;\n return tryOpenDB();\n }\n break;\n }\n return DexiePromise.reject(err);\n }); };\n return DexiePromise.race([\n openCanceller,\n (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB)\n ]).then(function () {\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders);\n }\n });\n }).finally(function () {\n if (state.openCanceller === openCanceller) {\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n }).catch(function (err) {\n state.dbOpenError = err;\n try {\n upgradeTransaction && upgradeTransaction.abort();\n }\n catch (_a) { }\n if (openCanceller === state.openCanceller) {\n db._close();\n }\n return rejection(err);\n }).finally(function () {\n state.openComplete = true;\n resolveDbReady();\n }).then(function () {\n if (wasCreated) {\n var everything_1 = {};\n db.tables.forEach(function (table) {\n table.schema.indexes.forEach(function (idx) {\n if (idx.name)\n everything_1[\"idb://\".concat(db.name, \"/\").concat(table.name, \"/\").concat(idx.name)] = new RangeSet(-Infinity, [[[]]]);\n });\n everything_1[\"idb://\".concat(db.name, \"/\").concat(table.name, \"/\")] = everything_1[\"idb://\".concat(db.name, \"/\").concat(table.name, \"/:dels\")] = new RangeSet(-Infinity, [[[]]]);\n });\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1);\n signalSubscribersNow(everything_1, true);\n }\n return db;\n });\n }\n\n function awaitIterator(iterator) {\n var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow);\n function step(getNext) {\n return function (val) {\n var next = getNext(val), value = next.value;\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n return step(callNext)();\n }\n\n function extractTransactionArgs(mode, _tableArgs_, scopeFunc) {\n var i = arguments.length;\n if (i < 2)\n throw new exceptions.InvalidArgument(\"Too few arguments\");\n var args = new Array(i - 1);\n while (--i)\n args[i - 1] = arguments[i];\n scopeFunc = args.pop();\n var tables = flatten(args);\n return [mode, tables, scopeFunc];\n }\n function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) {\n return DexiePromise.resolve().then(function () {\n var transless = PSD.transless || PSD;\n var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n trans.explicit = true;\n var zoneProps = {\n trans: trans,\n transless: transless\n };\n if (parentTransaction) {\n trans.idbtrans = parentTransaction.idbtrans;\n }\n else {\n try {\n trans.create();\n trans.idbtrans._explicit = true;\n db._state.PR1398_maxLoop = 3;\n }\n catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db.close({ disableAutoOpen: false });\n return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); });\n }\n return rejection(ex);\n }\n }\n var scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n var returnValue;\n var promiseFollowed = DexiePromise.follow(function () {\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n DexiePromise.resolve(returnValue).then(function (x) { return trans.active ?\n x\n : rejection(new exceptions.PrematureCommit(\"Transaction committed too early. See http://bit.ly/2kdckMn\")); })\n : promiseFollowed.then(function () { return returnValue; })).then(function (x) {\n if (parentTransaction)\n trans._resolve();\n return trans._completion.then(function () { return x; });\n }).catch(function (e) {\n trans._reject(e);\n return rejection(e);\n });\n });\n }\n\n function pad(a, value, count) {\n var result = isArray(a) ? a.slice() : [a];\n for (var i = 0; i < count; ++i)\n result.push(value);\n return result;\n }\n function createVirtualIndexMiddleware(down) {\n return __assign(__assign({}, down), { table: function (tableName) {\n var table = down.table(tableName);\n var schema = table.schema;\n var indexLookup = {};\n var allVirtualIndexes = [];\n function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) {\n var keyPathAlias = getKeyPathAlias(keyPath);\n var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []);\n var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length;\n var isVirtual = keyTail > 0;\n var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual\n ? \"\".concat(keyPathAlias, \"(virtual-from:\").concat(lowLevelIndex.name, \")\")\n : lowLevelIndex.name, lowLevelIndex: lowLevelIndex, isVirtual: isVirtual, keyTail: keyTail, keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique });\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n var virtualKeyPath = keyLength === 2 ?\n keyPath[0] :\n keyPath.slice(0, keyLength - 1);\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort(function (a, b) { return a.keyTail - b.keyTail; });\n return virtualIndex;\n }\n var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) {\n var index = _a[_i];\n addVirtualIndexes(index.keyPath, 0, index);\n }\n function findBestIndex(keyPath) {\n var result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n function translateRange(range, keyTail) {\n return {\n type: range.type === 1 ?\n 2 :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true,\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true\n };\n }\n function translateRequest(req) {\n var index = req.query.index;\n return index.isVirtual ? __assign(__assign({}, req), { query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail)\n } }) : req;\n }\n var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) {\n return table.count(translateRequest(req));\n }, query: function (req) {\n return table.query(translateRequest(req));\n }, openCursor: function (req) {\n var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength;\n if (!isVirtual)\n return table.openCursor(req);\n function createVirtualCursor(cursor) {\n function _continue(key) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)) :\n cursor.continue();\n }\n var virtualCursor = Object.create(cursor, {\n continue: { value: _continue },\n continuePrimaryKey: {\n value: function (key, primaryKey) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get: function () {\n return cursor.primaryKey;\n }\n },\n key: {\n get: function () {\n var key = cursor.key;\n return keyLength === 1 ?\n key[0] :\n key.slice(0, keyLength);\n }\n },\n value: {\n get: function () {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n return table.openCursor(translateRequest(req))\n .then(function (cursor) { return cursor && createVirtualCursor(cursor); });\n } });\n return result;\n } });\n }\n var virtualIndexMiddleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n };\n\n function getObjectDiff(a, b, rv, prfx) {\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach(function (prop) {\n if (!hasOwn(b, prop)) {\n rv[prfx + prop] = undefined;\n }\n else {\n var ap = a[prop], bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n var apTypeName = toStringTag(ap);\n var bpTypeName = toStringTag(bp);\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop];\n }\n else if (apTypeName === 'Object') {\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n }\n else if (ap !== bp) {\n rv[prfx + prop] = b[prop];\n }\n }\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];\n }\n });\n keys(b).forEach(function (prop) {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop];\n }\n });\n return rv;\n }\n\n function getEffectiveKeys(primaryKey, req) {\n if (req.type === 'delete')\n return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey);\n }\n\n var hooksMiddleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) {\n var downTable = downCore.table(tableName);\n var primaryKey = downTable.schema.primaryKey;\n var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) {\n var dxTrans = PSD.trans;\n var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop)\n break;\n return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop)\n break;\n return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true);\n case 'delete':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true);\n case 'deleteRange':\n if (deleting.fire === nop)\n break;\n return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true);\n }\n return downTable.mutate(req);\n function addPutOrDelete(req) {\n var dxTrans = PSD.trans;\n var keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys)\n throw new Error(\"Keys missing\");\n req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req);\n if (req.type !== 'delete')\n req.values = __spreadArray([], req.values, true);\n if (req.keys)\n req.keys = __spreadArray([], req.keys, true);\n return getExistingValues(downTable, req, keys).then(function (existingValues) {\n var contexts = keys.map(function (key, i) {\n var existingValue = existingValues[i];\n var ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n }\n else if (req.type === 'add' || existingValue === undefined) {\n var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n }\n else {\n var objectDiff = getObjectDiff(existingValue, req.values[i]);\n var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges_1) {\n var requestedValue_1 = req.values[i];\n Object.keys(additionalChanges_1).forEach(function (keyPath) {\n if (hasOwn(requestedValue_1, keyPath)) {\n requestedValue_1[keyPath] = additionalChanges_1[keyPath];\n }\n else {\n setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(function (_a) {\n var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult;\n for (var i = 0; i < keys.length; ++i) {\n var primKey = results ? results[i] : keys[i];\n var ctx = contexts[i];\n if (primKey == null) {\n ctx.onerror && ctx.onerror(failures[i]);\n }\n else {\n ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ?\n req.values[i] :\n primKey\n );\n }\n }\n return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult };\n }).catch(function (error) {\n contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); });\n return Promise.reject(error);\n });\n });\n }\n function deleteRange(req) {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n function deleteNextChunk(trans, range, limit) {\n return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit })\n .then(function (_a) {\n var result = _a.result;\n return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) {\n if (res.numFailures > 0)\n return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return { failures: [], numFailures: 0, lastResult: undefined };\n }\n else {\n return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit);\n }\n });\n });\n }\n } });\n return tableMiddleware;\n } })); }\n };\n function getExistingValues(table, req, effectiveKeys) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n }\n\n function getFromTransactionCache(keys, cache, clone) {\n try {\n if (!cache)\n return null;\n if (cache.keys.length < keys.length)\n return null;\n var result = [];\n for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0)\n continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n return result.length === keys.length ? result : null;\n }\n catch (_a) {\n return null;\n }\n }\n var cacheExistingValuesMiddleware = {\n stack: \"dbcore\",\n level: -1,\n create: function (core) {\n return {\n table: function (tableName) {\n var table = core.table(tableName);\n return __assign(__assign({}, table), { getMany: function (req) {\n if (!req.cache) {\n return table.getMany(req);\n }\n var cachedResult = getFromTransactionCache(req.keys, req.trans[\"_cache\"], req.cache === \"clone\");\n if (cachedResult) {\n return DexiePromise.resolve(cachedResult);\n }\n return table.getMany(req).then(function (res) {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n }, mutate: function (req) {\n if (req.type !== \"add\")\n req.trans[\"_cache\"] = null;\n return table.mutate(req);\n } });\n },\n };\n },\n };\n\n function isCachableContext(ctx, table) {\n return (ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound);\n }\n\n function isCachableRequest(type, req) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n }\n\n var observabilityMiddleware = {\n stack: \"dbcore\",\n level: 0,\n name: \"Observability\",\n create: function (core) {\n var dbName = core.schema.name;\n var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n return __assign(__assign({}, core), { transaction: function (stores, mode, options) {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(\"Readwrite transaction in liveQuery context. Querier source: \".concat(PSD.querier));\n }\n return core.transaction(stores, mode, options);\n }, table: function (tableName) {\n var table = core.table(tableName);\n var schema = table.schema;\n var primaryKey = schema.primaryKey, indexes = schema.indexes;\n var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound;\n var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function (index) { return index.compound && index.keyPath.includes(primaryKey.keyPath); });\n var tableClone = __assign(__assign({}, table), { mutate: function (req) {\n var _a, _b;\n var trans = req.trans;\n var mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n var getRangeSet = function (indexName) {\n var part = \"idb://\".concat(dbName, \"/\").concat(tableName, \"/\").concat(indexName);\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet()));\n };\n var pkRangeSet = getRangeSet(\"\");\n var delsRangeSet = getRangeSet(\":dels\");\n var type = req.type;\n var _c = req.type === \"deleteRange\"\n ? [req.range]\n : req.type === \"delete\"\n ? [req.keys]\n : req.values.length < 50\n ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values]\n : [], keys = _c[0], newObjs = _c[1];\n var oldCache = req.trans[\"_cache\"];\n if (isArray(keys)) {\n pkRangeSet.addKeys(keys);\n var oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null;\n if (!oldObjs) {\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n }\n else if (keys) {\n var range = {\n from: (_a = keys.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY,\n to: (_b = keys.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY\n };\n delsRangeSet.add(range);\n pkRangeSet.add(range);\n }\n else {\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); });\n }\n return table.mutate(req).then(function (res) {\n if (keys && (req.type === 'add' || req.type === 'put')) {\n pkRangeSet.addKeys(res.results);\n if (indexesWithAutoIncPK) {\n indexesWithAutoIncPK.forEach(function (idx) {\n var idxVals = req.values.map(function (v) { return idx.extractKey(v); });\n var pkPos = idx.keyPath.findIndex(function (prop) { return prop === primaryKey.keyPath; });\n for (var i = 0, len = res.results.length; i < len; ++i) {\n idxVals[i][pkPos] = res.results[i];\n }\n getRangeSet(idx.name).addKeys(idxVals);\n });\n }\n }\n trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts);\n return res;\n });\n } });\n var getRange = function (_a) {\n var _b, _c;\n var _d = _a.query, index = _d.index, range = _d.range;\n return [\n index,\n new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY),\n ];\n };\n var readSubscribers = {\n get: function (req) { return [primaryKey, new RangeSet(req.key)]; },\n getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; },\n count: getRange,\n query: getRange,\n openCursor: getRange,\n };\n keys(readSubscribers).forEach(function (method) {\n tableClone[method] = function (req) {\n var subscr = PSD.subscr;\n var isLiveQuery = !!subscr;\n var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req);\n var obsSet = cachable\n ? req.obsSet = {}\n : subscr;\n if (isLiveQuery) {\n var getRangeSet = function (indexName) {\n var part = \"idb://\".concat(dbName, \"/\").concat(tableName, \"/\").concat(indexName);\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet()));\n };\n var pkRangeSet_1 = getRangeSet(\"\");\n var delsRangeSet_1 = getRangeSet(\":dels\");\n var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1];\n if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) {\n delsRangeSet_1.add(queriedRanges);\n }\n else {\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n }\n if (!queriedIndex.isPrimaryKey) {\n if (method === \"count\") {\n delsRangeSet_1.add(FULL_RANGE);\n }\n else {\n var keysPromise_1 = method === \"query\" &&\n outbound &&\n req.values &&\n table.query(__assign(__assign({}, req), { values: false }));\n return table[method].apply(this, arguments).then(function (res) {\n if (method === \"query\") {\n if (outbound && req.values) {\n return keysPromise_1.then(function (_a) {\n var resultingKeys = _a.result;\n pkRangeSet_1.addKeys(resultingKeys);\n return res;\n });\n }\n var pKeys = req.values\n ? res.result.map(extractKey)\n : res.result;\n if (req.values) {\n pkRangeSet_1.addKeys(pKeys);\n }\n else {\n delsRangeSet_1.addKeys(pKeys);\n }\n }\n else if (method === \"openCursor\") {\n var cursor_1 = res;\n var wantValues_1 = req.values;\n return (cursor_1 &&\n Object.create(cursor_1, {\n key: {\n get: function () {\n delsRangeSet_1.addKey(cursor_1.primaryKey);\n return cursor_1.key;\n },\n },\n primaryKey: {\n get: function () {\n var pkey = cursor_1.primaryKey;\n delsRangeSet_1.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get: function () {\n wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey);\n return cursor_1.value;\n },\n },\n }));\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n } });\n },\n };\n function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) {\n function addAffectedIndex(ix) {\n var rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key)\n ? key.forEach(function (key) { return rangeSet.addKey(key); })\n : rangeSet.addKey(key); };\n (oldObjs || newObjs).forEach(function (_, i) {\n var oldKey = oldObjs && extractKey(oldObjs[i]);\n var newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n if (oldKey != null)\n addKeyOrKeys(oldKey);\n if (newKey != null)\n addKeyOrKeys(newKey);\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n }\n\n function adjustOptimisticFromFailures(tblCache, req, res) {\n if (res.numFailures === 0)\n return req;\n if (req.type === 'deleteRange') {\n return null;\n }\n var numBulkOps = req.keys\n ? req.keys.length\n : 'values' in req && req.values\n ? req.values.length\n : 1;\n if (res.numFailures === numBulkOps) {\n return null;\n }\n var clone = __assign({}, req);\n if (isArray(clone.keys)) {\n clone.keys = clone.keys.filter(function (_, i) { return !(i in res.failures); });\n }\n if ('values' in clone && isArray(clone.values)) {\n clone.values = clone.values.filter(function (_, i) { return !(i in res.failures); });\n }\n return clone;\n }\n\n function isAboveLower(key, range) {\n return range.lower === undefined\n ? true\n : range.lowerOpen\n ? cmp(key, range.lower) > 0\n : cmp(key, range.lower) >= 0;\n }\n function isBelowUpper(key, range) {\n return range.upper === undefined\n ? true\n : range.upperOpen\n ? cmp(key, range.upper) < 0\n : cmp(key, range.upper) <= 0;\n }\n function isWithinRange(key, range) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n }\n\n function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) {\n if (!ops || ops.length === 0)\n return result;\n var index = req.query.index;\n var multiEntry = index.multiEntry;\n var queryRange = req.query.range;\n var primaryKey = table.schema.primaryKey;\n var extractPrimKey = primaryKey.extractKey;\n var extractIndex = index.extractKey;\n var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey;\n var finalResult = ops.reduce(function (result, op) {\n var modifedResult = result;\n var includedValues = [];\n if (op.type === 'add' || op.type === 'put') {\n var includedPKs = new RangeSet();\n for (var i = op.values.length - 1; i >= 0; --i) {\n var value = op.values[i];\n var pk = extractPrimKey(value);\n if (includedPKs.hasKey(pk))\n continue;\n var key = extractIndex(value);\n if (multiEntry && isArray(key)\n ? key.some(function (k) { return isWithinRange(k, queryRange); })\n : isWithinRange(key, queryRange)) {\n includedPKs.addKey(pk);\n includedValues.push(value);\n }\n }\n }\n switch (op.type) {\n case 'add': {\n var existingKeys_1 = new RangeSet().addKeys(req.values ? result.map(function (v) { return extractPrimKey(v); }) : result);\n modifedResult = result.concat(req.values\n ? includedValues.filter(function (v) {\n var key = extractPrimKey(v);\n if (existingKeys_1.hasKey(key))\n return false;\n existingKeys_1.addKey(key);\n return true;\n })\n : includedValues\n .map(function (v) { return extractPrimKey(v); })\n .filter(function (k) {\n if (existingKeys_1.hasKey(k))\n return false;\n existingKeys_1.addKey(k);\n return true;\n }));\n break;\n }\n case 'put': {\n var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); }));\n modifedResult = result\n .filter(\n function (item) { return !keySet_1.hasKey(req.values ? extractPrimKey(item) : item); })\n .concat(\n req.values\n ? includedValues\n : includedValues.map(function (v) { return extractPrimKey(v); }));\n break;\n }\n case 'delete':\n var keysToDelete_1 = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter(function (item) {\n return !keysToDelete_1.hasKey(req.values ? extractPrimKey(item) : item);\n });\n break;\n case 'deleteRange':\n var range_1 = op.range;\n modifedResult = result.filter(function (item) { return !isWithinRange(extractPrimKey(item), range_1); });\n break;\n }\n return modifedResult;\n }, result);\n if (finalResult === result)\n return result;\n finalResult.sort(function (a, b) {\n return cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b));\n });\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit;\n }\n else if (result.length === req.limit && finalResult.length < req.limit) {\n cacheEntry.dirty = true;\n }\n }\n return immutable ? Object.freeze(finalResult) : finalResult;\n }\n\n function areRangesEqual(r1, r2) {\n return (cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen);\n }\n\n function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) {\n if (lower1 === undefined)\n return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined)\n return 1;\n var c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2)\n return 0;\n if (lowerOpen1)\n return 1;\n if (lowerOpen2)\n return -1;\n }\n return c;\n }\n function compareUppers(upper1, upper2, upperOpen1, upperOpen2) {\n if (upper1 === undefined)\n return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined)\n return -1;\n var c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2)\n return 0;\n if (upperOpen1)\n return -1;\n if (upperOpen2)\n return 1;\n }\n return c;\n }\n function isSuperRange(r1, r2) {\n return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0);\n }\n\n function findCompatibleQuery(dbName, tableName, type, req) {\n var tblCache = cache[\"idb://\".concat(dbName, \"/\").concat(tableName)];\n if (!tblCache)\n return [];\n var queries = tblCache.queries[type];\n if (!queries)\n return [null, false, tblCache, null];\n var indexName = req.query ? req.query.index.name : null;\n var entries = queries[indexName || ''];\n if (!entries)\n return [null, false, tblCache, null];\n switch (type) {\n case 'query':\n var equalEntry = entries.find(function (entry) {\n return entry.req.limit === req.limit &&\n entry.req.values === req.values &&\n areRangesEqual(entry.req.query.range, req.query.range);\n });\n if (equalEntry)\n return [\n equalEntry,\n true,\n tblCache,\n entries,\n ];\n var superEntry = entries.find(function (entry) {\n var limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (limit >= req.limit &&\n (req.values ? entry.req.values : true) &&\n isSuperRange(entry.req.query.range, req.query.range));\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n var countQuery = entries.find(function (entry) {\n return areRangesEqual(entry.req.query.range, req.query.range);\n });\n return [countQuery, !!countQuery, tblCache, entries];\n }\n }\n\n function subscribeToCacheEntry(cacheEntry, container, requery, signal) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener(\"abort\", function () {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n }\n function enqueForDeletion(cacheEntry, container) {\n setTimeout(function () {\n if (cacheEntry.subscribers.size === 0) {\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n }\n\n var cacheMiddleware = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: function (core) {\n var dbName = core.schema.name;\n var coreMW = __assign(__assign({}, core), { transaction: function (stores, mode, options) {\n var idbtrans = core.transaction(stores, mode, options);\n if (mode === 'readwrite') {\n var ac_1 = new AbortController();\n var signal = ac_1.signal;\n var endTransaction = function (wasCommitted) { return function () {\n ac_1.abort();\n if (mode === 'readwrite') {\n var affectedSubscribers_1 = new Set();\n for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) {\n var storeName = stores_1[_i];\n var tblCache = cache[\"idb://\".concat(dbName, \"/\").concat(storeName)];\n if (tblCache) {\n var table = core.table(storeName);\n var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });\n if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {\n for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) {\n var entries = _b[_a];\n for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) {\n var entry = _d[_c];\n if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {\n delArrayItem(entries, entry);\n entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });\n }\n }\n }\n }\n else if (ops.length > 0) {\n tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });\n for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) {\n var entries = _f[_e];\n for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) {\n var entry = _h[_g];\n if (entry.res != null &&\n idbtrans.mutatedParts\n ) {\n if (wasCommitted && !entry.dirty) {\n var freezeResults = Object.isFrozen(entry.res);\n var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);\n if (entry.dirty) {\n delArrayItem(entries, entry);\n entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });\n }\n else if (modRes !== entry.res) {\n entry.res = modRes;\n entry.promise = DexiePromise.resolve({ result: modRes });\n }\n }\n else {\n if (entry.dirty) {\n delArrayItem(entries, entry);\n }\n entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers_1.forEach(function (requery) { return requery(); });\n }\n }; };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal: signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal: signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal: signal,\n });\n }\n return idbtrans;\n }, table: function (tableName) {\n var downTable = core.table(tableName);\n var primKey = downTable.schema.primaryKey;\n var tableMW = __assign(__assign({}, downTable), { mutate: function (req) {\n var trans = PSD.trans;\n if (primKey.outbound ||\n trans.db._options.cache === 'disabled' ||\n trans.explicit ||\n trans.idbtrans.mode !== 'readwrite'\n ) {\n return downTable.mutate(req);\n }\n var tblCache = cache[\"idb://\".concat(dbName, \"/\").concat(tableName)];\n if (!tblCache)\n return downTable.mutate(req);\n var promise = downTable.mutate(req);\n if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function (key) { return key == null; }))) {\n promise.then(function (res) {\n var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function (value, i) {\n var _a;\n if (res.failures[i])\n return value;\n var valueWithKey = ((_a = primKey.keyPath) === null || _a === void 0 ? void 0 : _a.includes('.'))\n ? deepClone(value)\n : __assign({}, value);\n setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]);\n return valueWithKey;\n }) });\n var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res);\n tblCache.optimisticOps.push(adjustedReq);\n queueMicrotask(function () { return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); });\n });\n }\n else {\n tblCache.optimisticOps.push(req);\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts);\n promise.then(function (res) {\n if (res.numFailures > 0) {\n delArrayItem(tblCache.optimisticOps, req);\n var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res);\n if (adjustedReq) {\n tblCache.optimisticOps.push(adjustedReq);\n }\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts);\n }\n });\n promise.catch(function () {\n delArrayItem(tblCache.optimisticOps, req);\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts);\n });\n }\n return promise;\n }, query: function (req) {\n var _a;\n if (!isCachableContext(PSD, downTable) || !isCachableRequest(\"query\", req))\n return downTable.query(req);\n var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable';\n var _b = PSD, requery = _b.requery, signal = _b.signal;\n var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet;\n }\n else {\n var promise = downTable.query(req).then(function (res) {\n var result = res.result;\n if (cacheEntry)\n cacheEntry.res = result;\n if (freezeResults) {\n for (var i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n }\n else {\n res.result = deepClone(result);\n }\n return res;\n }).catch(function (error) {\n if (container && cacheEntry)\n delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet,\n promise: promise,\n subscribers: new Set(),\n type: 'query',\n req: req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n }\n else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[\"idb://\".concat(dbName, \"/\").concat(tableName)] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {}\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container, requery, signal);\n return cacheEntry.promise.then(function (res) {\n return {\n result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults),\n };\n });\n } });\n return tableMW;\n } });\n return coreMW;\n },\n };\n\n function vipify(target, vipDb) {\n return new Proxy(target, {\n get: function (target, prop, receiver) {\n if (prop === 'db')\n return vipDb;\n return Reflect.get(target, prop, receiver);\n }\n });\n }\n\n var Dexie$1 = (function () {\n function Dexie(name, options) {\n var _this = this;\n this._middlewares = {};\n this.verno = 0;\n var deps = Dexie.dependencies;\n this._options = options = __assign({\n addons: Dexie.addons, autoOpen: true,\n indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange, cache: 'cloned' }, options);\n this._deps = {\n indexedDB: options.indexedDB,\n IDBKeyRange: options.IDBKeyRange\n };\n var addons = options.addons;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n var state = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null,\n cancelOpen: nop,\n openCanceller: null,\n autoSchema: true,\n PR1398_maxLoop: 3,\n autoOpen: options.autoOpen,\n };\n state.dbReadyPromise = new DexiePromise(function (resolve) {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise(function (_, reject) {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] });\n this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {\n return function (subscriber, bSticky) {\n Dexie.vip(function () {\n var state = _this._state;\n if (state.openComplete) {\n if (!state.dbOpenError)\n DexiePromise.resolve().then(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else if (state.onReadyBeingFired) {\n state.onReadyBeingFired.push(subscriber);\n if (bSticky)\n subscribe(subscriber);\n }\n else {\n subscribe(subscriber);\n var db_1 = _this;\n if (!bSticky)\n subscribe(function unsubscribe() {\n db_1.on.ready.unsubscribe(subscriber);\n db_1.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n };\n });\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n this.on(\"versionchange\", function (ev) {\n if (ev.newVersion > 0)\n console.warn(\"Another connection wants to upgrade database '\".concat(_this.name, \"'. Closing db now to resume the upgrade.\"));\n else\n console.warn(\"Another connection wants to delete database '\".concat(_this.name, \"'. Closing db now to resume the delete request.\"));\n _this.close({ disableAutoOpen: false });\n });\n this.on(\"blocked\", function (ev) {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(\"Dexie.delete('\".concat(_this.name, \"') was blocked\"));\n else\n console.warn(\"Upgrade '\".concat(_this.name, \"' blocked by other connection holding version \").concat(ev.oldVersion / 10));\n });\n this._maxKey = getMaxKey(options.IDBKeyRange);\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); };\n this._fireOnBlocked = function (ev) {\n _this.on(\"blocked\").fire(ev);\n connections\n .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; })\n .map(function (c) { return c.on(\"versionchange\").fire(ev); });\n };\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n var vipDB = new Proxy(this, {\n get: function (_, prop, receiver) {\n if (prop === '_vip')\n return true;\n if (prop === 'table')\n return function (tableName) { return vipify(_this.table(tableName), vipDB); };\n var rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table)\n return vipify(rv, vipDB);\n if (prop === 'tables')\n return rv.map(function (t) { return vipify(t, vipDB); });\n if (prop === '_createTransaction')\n return function () {\n var tx = rv.apply(this, arguments);\n return vipify(tx, vipDB);\n };\n return rv;\n }\n });\n this.vip = vipDB;\n addons.forEach(function (addon) { return addon(_this); });\n }\n Dexie.prototype.version = function (versionNumber) {\n if (isNaN(versionNumber) || versionNumber < 0.1)\n throw new exceptions.Type(\"Given version is not a positive number\");\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versions = this._versions;\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\n if (versionInstance)\n return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({});\n this._state.autoSchema = false;\n return versionInstance;\n };\n Dexie.prototype._whenReady = function (fn) {\n var _this = this;\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) {\n if (_this._state.openComplete) {\n return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError));\n }\n if (!_this._state.isBeingOpened) {\n if (!_this._state.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n _this.open().catch(nop);\n }\n _this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n };\n Dexie.prototype.use = function (_a) {\n var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name;\n if (name)\n this.unuse({ stack: stack, name: name });\n var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name });\n middlewares.sort(function (a, b) { return a.level - b.level; });\n return this;\n };\n Dexie.prototype.unuse = function (_a) {\n var stack = _a.stack, name = _a.name, create = _a.create;\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(function (mw) {\n return create ? mw.create !== create :\n name ? mw.name !== name :\n false;\n });\n }\n return this;\n };\n Dexie.prototype.open = function () {\n var _this = this;\n return usePSD(globalPSD,\n function () { return dexieOpen(_this); });\n };\n Dexie.prototype._close = function () {\n var state = this._state;\n var idx = connections.indexOf(this);\n if (idx >= 0)\n connections.splice(idx, 1);\n if (this.idbdb) {\n try {\n this.idbdb.close();\n }\n catch (e) { }\n this.idbdb = null;\n }\n if (!state.isBeingOpened) {\n state.dbReadyPromise = new DexiePromise(function (resolve) {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new DexiePromise(function (_, reject) {\n state.cancelOpen = reject;\n });\n }\n };\n Dexie.prototype.close = function (_a) {\n var _b = _a === void 0 ? { disableAutoOpen: true } : _a, disableAutoOpen = _b.disableAutoOpen;\n var state = this._state;\n if (disableAutoOpen) {\n if (state.isBeingOpened) {\n state.cancelOpen(new exceptions.DatabaseClosed());\n }\n this._close();\n state.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n }\n else {\n this._close();\n state.autoOpen = this._options.autoOpen ||\n state.isBeingOpened;\n state.openComplete = false;\n state.dbOpenError = null;\n }\n };\n Dexie.prototype.delete = function (closeOptions) {\n var _this = this;\n if (closeOptions === void 0) { closeOptions = { disableAutoOpen: true }; }\n var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== 'object';\n var state = this._state;\n return new DexiePromise(function (resolve, reject) {\n var doDelete = function () {\n _this.close(closeOptions);\n var req = _this._deps.indexedDB.deleteDatabase(_this.name);\n req.onsuccess = wrap(function () {\n _onDatabaseDeleted(_this._deps, _this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = _this._fireOnBlocked;\n };\n if (hasInvalidArguments)\n throw new exceptions.InvalidArgument(\"Invalid closeOptions argument to db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n }\n else {\n doDelete();\n }\n });\n };\n Dexie.prototype.backendDB = function () {\n return this.idbdb;\n };\n Dexie.prototype.isOpen = function () {\n return this.idbdb !== null;\n };\n Dexie.prototype.hasBeenClosed = function () {\n var dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n };\n Dexie.prototype.hasFailed = function () {\n return this._state.dbOpenError !== null;\n };\n Dexie.prototype.dynamicallyOpened = function () {\n return this._state.autoSchema;\n };\n Object.defineProperty(Dexie.prototype, \"tables\", {\n get: function () {\n var _this = this;\n return keys(this._allTables).map(function (name) { return _this._allTables[name]; });\n },\n enumerable: false,\n configurable: true\n });\n Dexie.prototype.transaction = function () {\n var args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n };\n Dexie.prototype._transaction = function (mode, tables, scopeFunc) {\n var _this = this;\n var parentTransaction = PSD.trans;\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1)\n parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '');\n var idbMode, storeNames;\n try {\n storeNames = tables.map(function (table) {\n var storeName = table instanceof _this.Table ? table.name : table;\n if (typeof storeName !== 'string')\n throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n if (parentTransaction) {\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n parentTransaction = null;\n }\n else\n throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n parentTransaction = null;\n }\n }\n }\n catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, function (_, reject) { reject(e); }) :\n rejection(e);\n }\n var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) :\n this._whenReady(enterTransaction));\n };\n Dexie.prototype.table = function (tableName) {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(\"Table \".concat(tableName, \" does not exist\"));\n }\n return this._allTables[tableName];\n };\n return Dexie;\n }());\n\n var symbolObservable = typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\";\n var Observable = (function () {\n function Observable(subscribe) {\n this._subscribe = subscribe;\n }\n Observable.prototype.subscribe = function (x, error, complete) {\n return this._subscribe(!x || typeof x === \"function\" ? { next: x, error: error, complete: complete } : x);\n };\n Observable.prototype[symbolObservable] = function () {\n return this;\n };\n return Observable;\n }());\n\n var domDeps;\n try {\n domDeps = {\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n }\n catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n }\n\n function liveQuery(querier) {\n var hasValue = false;\n var currentValue;\n var observable = new Observable(function (observer) {\n var scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx) {\n var wasRootExec = beginMicroTickScope();\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n var rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n rv = rv.finally(decrementExpectedAwaits);\n }\n return rv;\n }\n finally {\n wasRootExec && endMicroTickScope();\n }\n }\n var closed = false;\n var abortController;\n var accumMuts = {};\n var currentObs = {};\n var subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: function () {\n if (closed)\n return;\n closed = true;\n if (abortController)\n abortController.abort();\n if (startedListening)\n globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n observer.start && observer.start(subscription);\n var startedListening = false;\n var doQuery = function () { return execInGlobalContext(_doQuery); };\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n var mutationListener = function (parts) {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n var _doQuery = function () {\n if (closed ||\n !domDeps.indexedDB)\n {\n return;\n }\n accumMuts = {};\n var subscr = {};\n if (abortController)\n abortController.abort();\n abortController = new AbortController();\n var ctx = {\n subscr: subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier: querier,\n trans: null\n };\n var ret = execute(ctx);\n Promise.resolve(ret).then(function (result) {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n return;\n }\n accumMuts = {};\n currentObs = subscr;\n if (!objectIsEmpty(currentObs) && !startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n execInGlobalContext(function () { return !closed && observer.next && observer.next(result); });\n }, function (err) {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) {\n if (!closed)\n execInGlobalContext(function () {\n if (closed)\n return;\n observer.error && observer.error(err);\n });\n }\n });\n };\n setTimeout(doQuery, 0);\n return subscription;\n });\n observable.hasValue = function () { return hasValue; };\n observable.getValue = function () { return currentValue; };\n return observable;\n }\n\n var Dexie = Dexie$1;\n props(Dexie, __assign(__assign({}, fullNameExceptions), {\n delete: function (databaseName) {\n var db = new Dexie(databaseName, { addons: [] });\n return db.delete();\n },\n exists: function (name) {\n return new Dexie(name, { addons: [] }).open().then(function (db) {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', function () { return false; });\n },\n getDatabaseNames: function (cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n }\n catch (_a) {\n return rejection(new exceptions.MissingAPI());\n }\n },\n defineClass: function () {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n }, ignoreTransaction: function (scopeFunc) {\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) :\n scopeFunc();\n }, vip: vip, async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n };\n }, spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return DexiePromise.resolve(rv);\n return rv;\n }\n catch (e) {\n return rejection(e);\n }\n },\n currentTransaction: {\n get: function () { return PSD.trans || null; }\n }, waitFor: function (promiseOrFunction, optionalTimeout) {\n var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000);\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n Promise: DexiePromise,\n debug: {\n get: function () { return debug; },\n set: function (value) {\n setDebug(value);\n }\n },\n derive: derive, extend: extend, props: props, override: override,\n Events: Events, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet,\n getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1,\n minKey: minKey,\n addons: [],\n connections: connections,\n errnames: errnames,\n dependencies: domDeps, cache: cache,\n semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.')\n .map(function (n) { return parseInt(n); })\n .reduce(function (p, c, i) { return p + (c / Math.pow(10, i * 2)); }) }));\n Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n\n if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) {\n if (!propagatingLocally) {\n var event_1;\n event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n propagatingLocally = true;\n dispatchEvent(event_1);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) {\n var detail = _a.detail;\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n }\n function propagateLocally(updateParts) {\n var wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n globalEvents.storagemutated.fire(updateParts);\n signalSubscribersNow(updateParts, true);\n }\n finally {\n propagatingLocally = wasMe;\n }\n }\n var propagatingLocally = false;\n\n var bc;\n var createBC = function () { };\n if (typeof BroadcastChannel !== 'undefined') {\n createBC = function () {\n bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n bc.onmessage = function (ev) { return ev.data && propagateLocally(ev.data); };\n };\n createBC();\n if (typeof bc.unref === 'function') {\n bc.unref();\n }\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n }\n\n if (typeof addEventListener !== 'undefined') {\n addEventListener('pagehide', function (event) {\n if (!Dexie$1.disableBfCache && event.persisted) {\n if (debug)\n console.debug('Dexie: handling persisted pagehide');\n bc === null || bc === void 0 ? void 0 : bc.close();\n for (var _i = 0, connections_1 = connections; _i < connections_1.length; _i++) {\n var db = connections_1[_i];\n db.close({ disableAutoOpen: false });\n }\n }\n });\n addEventListener('pageshow', function (event) {\n if (!Dexie$1.disableBfCache && event.persisted) {\n if (debug)\n console.debug('Dexie: handling persisted pageshow');\n createBC();\n propagateLocally({ all: new RangeSet(-Infinity, [[]]) });\n }\n });\n }\n\n function add(value) {\n return new PropModification({ add: value });\n }\n\n function remove(value) {\n return new PropModification({ remove: value });\n }\n\n function replacePrefix(a, b) {\n return new PropModification({ replacePrefix: [a, b] });\n }\n\n DexiePromise.rejectionMapper = mapError;\n setDebug(debug);\n\n var namedExports = /*#__PURE__*/Object.freeze({\n __proto__: null,\n Dexie: Dexie$1,\n liveQuery: liveQuery,\n Entity: Entity,\n cmp: cmp,\n PropModSymbol: PropModSymbol,\n PropModification: PropModification,\n replacePrefix: replacePrefix,\n add: add,\n remove: remove,\n 'default': Dexie$1,\n RangeSet: RangeSet,\n mergeRanges: mergeRanges,\n rangesOverlap: rangesOverlap\n });\n\n __assign(Dexie$1, namedExports, { default: Dexie$1 });\n\n return Dexie$1;\n\n}));\n//# sourceMappingURL=dexie.js.map\n","// NOTE: Update the ?v= number in the service worker after changes to this file.\r\n\r\n// Create/open the leanforms database.\r\nvar indexedDatabase = new Dexie(\"LeanForms\");\r\n\r\n// Create stores/tables.\r\n// Fields in strings are indexed, fields in comment are also stored.\r\nindexedDatabase.version(5).stores({\r\n // lastChange, lists, html, toolbar, init, matrices.\r\n formTypes: \"baseId, id\",\r\n formTypeUsers: \"++id, formTypeBaseId, userId\",\r\n\r\n // type, data, questionId.\r\n attachments: \"++id\",\r\n\r\n // action, formTypeId, baseId, data, attachments, matrixAttachments, createdAt, title.\r\n forms: \"++id, userId\",\r\n\r\n // Delete webforms table, renamed to forms.\r\n webforms: null,\r\n\r\n // guid, code, action.\r\n syncedForms: \"id, userId\",\r\n\r\n // value.\r\n organizationUnits: \"key\"\r\n}).upgrade(transaction => {\r\n // Rename webforms table to forms.\r\n return transaction.webforms?.toArray().then(forms => {\r\n return transaction.forms.bulkAdd(forms);\r\n });\r\n});\r\n","// Date calculation prototype methods.\r\nDate.prototype.addSeconds = function (seconds) {\r\n this.setSeconds(this.getSeconds() + seconds);\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addMinutes = function (minutes) {\r\n this.setMinutes(this.getMinutes() + minutes);\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addHours = function (hours) {\r\n this.setHours(this.getHours() + hours);\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addDays = function (days) {\r\n this.setDate(this.getDate() + days);\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addWeeks = function (weeks) {\r\n this.addDays(weeks * 7);\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addMonths = function (months) {\r\n let dt = this.getDate();\r\n this.setMonth(this.getMonth() + months);\r\n\r\n let currDt = this.getDate();\r\n if (dt !== currDt) {\r\n this.addDays(-currDt);\r\n }\r\n\r\n return this;\r\n};\r\n\r\nDate.prototype.addYears = function (years) {\r\n let dt = this.getDate();\r\n this.setFullYear(this.getFullYear() + years);\r\n\r\n let currDt = this.getDate();\r\n if (dt !== currDt) {\r\n this.addDays(-currDt);\r\n }\r\n\r\n return this;\r\n};"],"mappings":";CAEA,SAAWA,OAAQC,gBACVC,UAAY,iBAAmBC,SAAW,YAAcA,OAAOD,QAAUD,iBACzEG,SAAW,YAAcA,OAAOC,IAAMD,OAAOH,UACnDD,cAAgBM,aAAe,YAAcA,WAAaN,QAAUO,KAAMP,OAAOQ,UAAYP,UAC/F,EAJD,CAIGQ,MAAM,WAAe,aAEtB,MAAMC,QACGC,eACOC,SACNC,eACMC,0BAEZC,OACJ,IAAIC,OACIC,KACFC,QAEFH,OACJ,IAAII,MACGC,kBAEIC,UAAY,aAAeA,QACtC,IAAKL,OAAQ,CACXA,OAAS,SAASA,OAAOM,GACvB,OAAOA,CACT,CACF,CACA,IAAKL,KAAM,CACTA,KAAO,SAASA,KAAKK,GACnB,OAAOA,CACT,CACF,CACA,IAAKH,MAAO,CACVA,MAAQ,SAASA,MAAMI,IAAKC,UAAWC,MACrC,OAAOF,IAAIJ,MAAMK,UAAWC,KAC9B,CACF,CACA,IAAKL,UAAW,CACdA,UAAY,SAASA,UAAUM,KAAMD,MACnC,OAAO,IAAIC,QAAQD,KACrB,CACF,CACA,MAAME,a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