diff --git a/.gitignore b/.gitignore index e5aaad4..33157e1 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,8 @@ DexieNETCloudSample/wwwroot/importfile.json DexieNET/yarn/node_modules DexieNET/yarn/yarn.lock .DS_Store +.idea DexieCloudNET/yarn/node_modules +DexieCloudNET/yarn/src/**/*.js +DexieCloudNET/wwwroot/ +DexieCloudNET/yarn/src/DexieNET diff --git a/DexieCloudNET/DexieCloudNET.csproj b/DexieCloudNET/DexieCloudNET.csproj index d16e384..a517aa1 100644 --- a/DexieCloudNET/DexieCloudNET.csproj +++ b/DexieCloudNET/DexieCloudNET.csproj @@ -59,6 +59,17 @@ + + + + + + + + diff --git a/DexieCloudNET/wwwroot/js/dexieCloudNET.js b/DexieCloudNET/wwwroot/js/dexieCloudNET.js deleted file mode 100644 index 5e97cf6..0000000 --- a/DexieCloudNET/wwwroot/js/dexieCloudNET.js +++ /dev/null @@ -1,22992 +0,0 @@ -/******/ var __webpack_modules__ = ({ - -/***/ "./node_modules/dexie/dist/dexie.js": -/*!******************************************!*\ - !*** ./node_modules/dexie/dist/dexie.js ***! - \******************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* - * Dexie.js - a minimalistic wrapper for IndexedDB - * =============================================== - * - * By David Fahlander, david.fahlander@gmail.com - * - * Version 4.0.4, Wed Apr 10 2024 - * - * https://dexie.org - * - * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ - */ - -(function (global, factory) { - true ? module.exports = factory() : - 0; -})(this, (function () { 'use strict'; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - - var _global = typeof globalThis !== 'undefined' ? globalThis : - typeof self !== 'undefined' ? self : - typeof window !== 'undefined' ? window : - __webpack_require__.g; - - var keys = Object.keys; - var isArray = Array.isArray; - if (typeof Promise !== 'undefined' && !_global.Promise) { - _global.Promise = Promise; - } - function extend(obj, extension) { - if (typeof extension !== 'object') - return obj; - keys(extension).forEach(function (key) { - obj[key] = extension[key]; - }); - return obj; - } - var getProto = Object.getPrototypeOf; - var _hasOwn = {}.hasOwnProperty; - function hasOwn(obj, prop) { - return _hasOwn.call(obj, prop); - } - function props(proto, extension) { - if (typeof extension === 'function') - extension = extension(getProto(proto)); - (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function (key) { - setProp(proto, key, extension[key]); - }); - } - var defineProperty = Object.defineProperty; - function setProp(obj, prop, functionOrGetSet, options) { - defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? - { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : - { value: functionOrGetSet, configurable: true, writable: true }, options)); - } - function derive(Child) { - return { - from: function (Parent) { - Child.prototype = Object.create(Parent.prototype); - setProp(Child.prototype, "constructor", Child); - return { - extend: props.bind(null, Child.prototype) - }; - } - }; - } - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function getPropertyDescriptor(obj, prop) { - var pd = getOwnPropertyDescriptor(obj, prop); - var proto; - return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); - } - var _slice = [].slice; - function slice(args, start, end) { - return _slice.call(args, start, end); - } - function override(origFunc, overridedFactory) { - return overridedFactory(origFunc); - } - function assert(b) { - if (!b) - throw new Error("Assertion Failed"); - } - function asap$1(fn) { - if (_global.setImmediate) - setImmediate(fn); - else - setTimeout(fn, 0); - } - function arrayToObject(array, extractor) { - return array.reduce(function (result, item, i) { - var nameAndValue = extractor(item, i); - if (nameAndValue) - result[nameAndValue[0]] = nameAndValue[1]; - return result; - }, {}); - } - function getByKeyPath(obj, keyPath) { - if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) - return obj[keyPath]; - if (!keyPath) - return obj; - if (typeof keyPath !== 'string') { - var rv = []; - for (var i = 0, l = keyPath.length; i < l; ++i) { - var val = getByKeyPath(obj, keyPath[i]); - rv.push(val); - } - return rv; - } - var period = keyPath.indexOf('.'); - if (period !== -1) { - var innerObj = obj[keyPath.substr(0, period)]; - return innerObj == null ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); - } - return undefined; - } - function setByKeyPath(obj, keyPath, value) { - if (!obj || keyPath === undefined) - return; - if ('isFrozen' in Object && Object.isFrozen(obj)) - return; - if (typeof keyPath !== 'string' && 'length' in keyPath) { - assert(typeof value !== 'string' && 'length' in value); - for (var i = 0, l = keyPath.length; i < l; ++i) { - setByKeyPath(obj, keyPath[i], value[i]); - } - } - else { - var period = keyPath.indexOf('.'); - if (period !== -1) { - var currentKeyPath = keyPath.substr(0, period); - var remainingKeyPath = keyPath.substr(period + 1); - if (remainingKeyPath === "") - if (value === undefined) { - if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) - obj.splice(currentKeyPath, 1); - else - delete obj[currentKeyPath]; - } - else - obj[currentKeyPath] = value; - else { - var innerObj = obj[currentKeyPath]; - if (!innerObj || !hasOwn(obj, currentKeyPath)) - innerObj = (obj[currentKeyPath] = {}); - setByKeyPath(innerObj, remainingKeyPath, value); - } - } - else { - if (value === undefined) { - if (isArray(obj) && !isNaN(parseInt(keyPath))) - obj.splice(keyPath, 1); - else - delete obj[keyPath]; - } - else - obj[keyPath] = value; - } - } - } - function delByKeyPath(obj, keyPath) { - if (typeof keyPath === 'string') - setByKeyPath(obj, keyPath, undefined); - else if ('length' in keyPath) - [].map.call(keyPath, function (kp) { - setByKeyPath(obj, kp, undefined); - }); - } - function shallowClone(obj) { - var rv = {}; - for (var m in obj) { - if (hasOwn(obj, m)) - rv[m] = obj[m]; - } - return rv; - } - var concat = [].concat; - function flatten(a) { - return concat.apply([], a); - } - var intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" - .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }); - var intrinsicTypes = new Set(intrinsicTypeNames.map(function (t) { return _global[t]; })); - function cloneSimpleObjectTree(o) { - var rv = {}; - for (var k in o) - if (hasOwn(o, k)) { - var v = o[k]; - rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); - } - return rv; - } - function objectIsEmpty(o) { - for (var k in o) - if (hasOwn(o, k)) - return false; - return true; - } - var circularRefs = null; - function deepClone(any) { - circularRefs = new WeakMap(); - var rv = innerDeepClone(any); - circularRefs = null; - return rv; - } - function innerDeepClone(x) { - if (!x || typeof x !== 'object') - return x; - var rv = circularRefs.get(x); - if (rv) - return rv; - if (isArray(x)) { - rv = []; - circularRefs.set(x, rv); - for (var i = 0, l = x.length; i < l; ++i) { - rv.push(innerDeepClone(x[i])); - } - } - else if (intrinsicTypes.has(x.constructor)) { - rv = x; - } - else { - var proto = getProto(x); - rv = proto === Object.prototype ? {} : Object.create(proto); - circularRefs.set(x, rv); - for (var prop in x) { - if (hasOwn(x, prop)) { - rv[prop] = innerDeepClone(x[prop]); - } - } - } - return rv; - } - var toString = {}.toString; - function toStringTag(o) { - return toString.call(o).slice(8, -1); - } - var iteratorSymbol = typeof Symbol !== 'undefined' ? - Symbol.iterator : - '@@iterator'; - var getIteratorOf = typeof iteratorSymbol === "symbol" ? function (x) { - var i; - return x != null && (i = x[iteratorSymbol]) && i.apply(x); - } : function () { return null; }; - function delArrayItem(a, x) { - var i = a.indexOf(x); - if (i >= 0) - a.splice(i, 1); - return i >= 0; - } - var NO_CHAR_ARRAY = {}; - function getArrayOf(arrayLike) { - var i, a, x, it; - if (arguments.length === 1) { - if (isArray(arrayLike)) - return arrayLike.slice(); - if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') - return [arrayLike]; - if ((it = getIteratorOf(arrayLike))) { - a = []; - while ((x = it.next()), !x.done) - a.push(x.value); - return a; - } - if (arrayLike == null) - return [arrayLike]; - i = arrayLike.length; - if (typeof i === 'number') { - a = new Array(i); - while (i--) - a[i] = arrayLike[i]; - return a; - } - return [arrayLike]; - } - i = arguments.length; - a = new Array(i); - while (i--) - a[i] = arguments[i]; - return a; - } - var isAsyncFunction = typeof Symbol !== 'undefined' - ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } - : function () { return false; }; - - var dexieErrorNames = [ - 'Modify', - 'Bulk', - 'OpenFailed', - 'VersionChange', - 'Schema', - 'Upgrade', - 'InvalidTable', - 'MissingAPI', - 'NoSuchDatabase', - 'InvalidArgument', - 'SubTransaction', - 'Unsupported', - 'Internal', - 'DatabaseClosed', - 'PrematureCommit', - 'ForeignAwait' - ]; - var idbDomErrorNames = [ - 'Unknown', - 'Constraint', - 'Data', - 'TransactionInactive', - 'ReadOnly', - 'Version', - 'NotFound', - 'InvalidState', - 'InvalidAccess', - 'Abort', - 'Timeout', - 'QuotaExceeded', - 'Syntax', - 'DataClone' - ]; - var errorList = dexieErrorNames.concat(idbDomErrorNames); - var defaultTexts = { - VersionChanged: "Database version changed by other database connection", - DatabaseClosed: "Database has been closed", - Abort: "Transaction aborted", - TransactionInactive: "Transaction has already completed or failed", - MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" - }; - function DexieError(name, msg) { - this.name = name; - this.message = msg; - } - derive(DexieError).from(Error).extend({ - toString: function () { return this.name + ": " + this.message; } - }); - function getMultiErrorMessage(msg, failures) { - return msg + ". Errors: " + Object.keys(failures) - .map(function (key) { return failures[key].toString(); }) - .filter(function (v, i, s) { return s.indexOf(v) === i; }) - .join('\n'); - } - function ModifyError(msg, failures, successCount, failedKeys) { - this.failures = failures; - this.failedKeys = failedKeys; - this.successCount = successCount; - this.message = getMultiErrorMessage(msg, failures); - } - derive(ModifyError).from(DexieError); - function BulkError(msg, failures) { - this.name = "BulkError"; - this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; }); - this.failuresByPos = failures; - this.message = getMultiErrorMessage(msg, this.failures); - } - derive(BulkError).from(DexieError); - var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); - var BaseException = DexieError; - var exceptions = errorList.reduce(function (obj, name) { - var fullName = name + "Error"; - function DexieError(msgOrInner, inner) { - this.name = fullName; - if (!msgOrInner) { - this.message = defaultTexts[name] || fullName; - this.inner = null; - } - else if (typeof msgOrInner === 'string') { - this.message = "".concat(msgOrInner).concat(!inner ? '' : '\n ' + inner); - this.inner = inner || null; - } - else if (typeof msgOrInner === 'object') { - this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); - this.inner = msgOrInner; - } - } - derive(DexieError).from(BaseException); - obj[name] = DexieError; - return obj; - }, {}); - exceptions.Syntax = SyntaxError; - exceptions.Type = TypeError; - exceptions.Range = RangeError; - var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - function mapError(domError, message) { - if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) - return domError; - var rv = new exceptionMap[domError.name](message || domError.message, domError); - if ("stack" in domError) { - setProp(rv, "stack", { get: function () { - return this.inner.stack; - } }); - } - return rv; - } - var fullNameExceptions = errorList.reduce(function (obj, name) { - if (["Syntax", "Type", "Range"].indexOf(name) === -1) - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - fullNameExceptions.ModifyError = ModifyError; - fullNameExceptions.DexieError = DexieError; - fullNameExceptions.BulkError = BulkError; - - function nop() { } - function mirror(val) { return val; } - function pureFunctionChain(f1, f2) { - if (f1 == null || f1 === mirror) - return f2; - return function (val) { - return f2(f1(val)); - }; - } - function callBoth(on1, on2) { - return function () { - on1.apply(this, arguments); - on2.apply(this, arguments); - }; - } - function hookCreatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - var res = f1.apply(this, arguments); - if (res !== undefined) - arguments[0] = res; - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res2 !== undefined ? res2 : res; - }; - } - function hookDeletingChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - f1.apply(this, arguments); - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = this.onerror = null; - f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - }; - } - function hookUpdatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function (modifications) { - var res = f1.apply(this, arguments); - extend(modifications, res); - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res === undefined ? - (res2 === undefined ? undefined : res2) : - (extend(res, res2)); - }; - } - function reverseStoppableEventChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - if (f2.apply(this, arguments) === false) - return false; - return f1.apply(this, arguments); - }; - } - function promisableChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - var res = f1.apply(this, arguments); - if (res && typeof res.then === 'function') { - var thiz = this, i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - return res.then(function () { - return f2.apply(thiz, args); - }); - } - return f2.apply(this, arguments); - }; - } - - var debug = typeof location !== 'undefined' && - /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); - function setDebug(value, filter) { - debug = value; - } - - var INTERNAL = {}; - var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? - [] : - (function () { - var globalP = Promise.resolve(); - if (typeof crypto === 'undefined' || !crypto.subtle) - return [globalP, getProto(globalP), globalP]; - var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); - return [ - nativeP, - getProto(nativeP), - globalP - ]; - })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; - var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; - var patchGlobalPromise = !!resolvedGlobalPromise; - function schedulePhysicalTick() { - queueMicrotask(physicalTick); - } - var asap = function (callback, args) { - microtickQueue.push([callback, args]); - if (needsNewPhysicalTick) { - schedulePhysicalTick(); - needsNewPhysicalTick = false; - } - }; - var isOutsideMicroTick = true, - needsNewPhysicalTick = true, - unhandledErrors = [], - rejectingErrors = [], - rejectionMapper = mirror; - var globalPSD = { - id: 'global', - global: true, - ref: 0, - unhandleds: [], - onunhandled: nop, - pgp: false, - env: {}, - finalize: nop - }; - var PSD = globalPSD; - var microtickQueue = []; - var numScheduledCalls = 0; - var tickFinalizers = []; - function DexiePromise(fn) { - if (typeof this !== 'object') - throw new TypeError('Promises must be constructed via new'); - this._listeners = []; - this._lib = false; - var psd = (this._PSD = PSD); - if (typeof fn !== 'function') { - if (fn !== INTERNAL) - throw new TypeError('Not a function'); - this._state = arguments[1]; - this._value = arguments[2]; - if (this._state === false) - handleRejection(this, this._value); - return; - } - this._state = null; - this._value = null; - ++psd.ref; - executePromiseTask(this, fn); - } - var thenProp = { - get: function () { - var psd = PSD, microTaskId = totalEchoes; - function then(onFulfilled, onRejected) { - var _this = this; - var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); - var cleanup = possibleAwait && !decrementExpectedAwaits(); - var rv = new DexiePromise(function (resolve, reject) { - propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); - }); - if (this._consoleTask) - rv._consoleTask = this._consoleTask; - return rv; - } - then.prototype = INTERNAL; - return then; - }, - set: function (value) { - setProp(this, 'then', value && value.prototype === INTERNAL ? - thenProp : - { - get: function () { - return value; - }, - set: thenProp.set - }); - } - }; - props(DexiePromise.prototype, { - then: thenProp, - _then: function (onFulfilled, onRejected) { - propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); - }, - catch: function (onRejected) { - if (arguments.length === 1) - return this.then(null, onRejected); - var type = arguments[0], handler = arguments[1]; - return typeof type === 'function' ? this.then(null, function (err) { - return err instanceof type ? handler(err) : PromiseReject(err); - }) - : this.then(null, function (err) { - return err && err.name === type ? handler(err) : PromiseReject(err); - }); - }, - finally: function (onFinally) { - return this.then(function (value) { - return DexiePromise.resolve(onFinally()).then(function () { return value; }); - }, function (err) { - return DexiePromise.resolve(onFinally()).then(function () { return PromiseReject(err); }); - }); - }, - timeout: function (ms, msg) { - var _this = this; - return ms < Infinity ? - new DexiePromise(function (resolve, reject) { - var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); - _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); - }) : this; - } - }); - if (typeof Symbol !== 'undefined' && Symbol.toStringTag) - setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); - globalPSD.env = snapShot(); - function Listener(onFulfilled, onRejected, resolve, reject, zone) { - this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; - this.onRejected = typeof onRejected === 'function' ? onRejected : null; - this.resolve = resolve; - this.reject = reject; - this.psd = zone; - } - props(DexiePromise, { - all: function () { - var values = getArrayOf.apply(null, arguments) - .map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - if (values.length === 0) - resolve([]); - var remaining = values.length; - values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { - values[i] = x; - if (!--remaining) - resolve(values); - }, reject); }); - }); - }, - resolve: function (value) { - if (value instanceof DexiePromise) - return value; - if (value && typeof value.then === 'function') - return new DexiePromise(function (resolve, reject) { - value.then(resolve, reject); - }); - var rv = new DexiePromise(INTERNAL, true, value); - return rv; - }, - reject: PromiseReject, - race: function () { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); - }); - }, - PSD: { - get: function () { return PSD; }, - set: function (value) { return PSD = value; } - }, - totalEchoes: { get: function () { return totalEchoes; } }, - newPSD: newScope, - usePSD: usePSD, - scheduler: { - get: function () { return asap; }, - set: function (value) { asap = value; } - }, - rejectionMapper: { - get: function () { return rejectionMapper; }, - set: function (value) { rejectionMapper = value; } - }, - follow: function (fn, zoneProps) { - return new DexiePromise(function (resolve, reject) { - return newScope(function (resolve, reject) { - var psd = PSD; - psd.unhandleds = []; - psd.onunhandled = reject; - psd.finalize = callBoth(function () { - var _this = this; - run_at_end_of_this_or_next_physical_tick(function () { - _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); - }); - }, psd.finalize); - fn(); - }, zoneProps, resolve, reject); - }); - } - }); - if (NativePromise) { - if (NativePromise.allSettled) - setProp(DexiePromise, "allSettled", function () { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve) { - if (possiblePromises.length === 0) - resolve([]); - var remaining = possiblePromises.length; - var results = new Array(remaining); - possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) - .then(function () { return --remaining || resolve(results); }); }); - }); - }); - if (NativePromise.any && typeof AggregateError !== 'undefined') - setProp(DexiePromise, "any", function () { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - if (possiblePromises.length === 0) - reject(new AggregateError([])); - var remaining = possiblePromises.length; - var failures = new Array(remaining); - possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { - failures[i] = failure; - if (!--remaining) - reject(new AggregateError(failures)); - }); }); - }); - }); - } - function executePromiseTask(promise, fn) { - try { - fn(function (value) { - if (promise._state !== null) - return; - if (value === promise) - throw new TypeError('A promise cannot be resolved with itself.'); - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - if (value && typeof value.then === 'function') { - executePromiseTask(promise, function (resolve, reject) { - value instanceof DexiePromise ? - value._then(resolve, reject) : - value.then(resolve, reject); - }); - } - else { - promise._state = true; - promise._value = value; - propagateAllListeners(promise); - } - if (shouldExecuteTick) - endMicroTickScope(); - }, handleRejection.bind(null, promise)); - } - catch (ex) { - handleRejection(promise, ex); - } - } - function handleRejection(promise, reason) { - rejectingErrors.push(reason); - if (promise._state !== null) - return; - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - reason = rejectionMapper(reason); - promise._state = false; - promise._value = reason; - addPossiblyUnhandledError(promise); - propagateAllListeners(promise); - if (shouldExecuteTick) - endMicroTickScope(); - } - function propagateAllListeners(promise) { - var listeners = promise._listeners; - promise._listeners = []; - for (var i = 0, len = listeners.length; i < len; ++i) { - propagateToListener(promise, listeners[i]); - } - var psd = promise._PSD; - --psd.ref || psd.finalize(); - if (numScheduledCalls === 0) { - ++numScheduledCalls; - asap(function () { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - } - function propagateToListener(promise, listener) { - if (promise._state === null) { - promise._listeners.push(listener); - return; - } - var cb = promise._state ? listener.onFulfilled : listener.onRejected; - if (cb === null) { - return (promise._state ? listener.resolve : listener.reject)(promise._value); - } - ++listener.psd.ref; - ++numScheduledCalls; - asap(callListener, [cb, promise, listener]); - } - function callListener(cb, promise, listener) { - try { - var ret, value = promise._value; - if (!promise._state && rejectingErrors.length) - rejectingErrors = []; - ret = debug && promise._consoleTask ? promise._consoleTask.run(function () { return cb(value); }) : cb(value); - if (!promise._state && rejectingErrors.indexOf(value) === -1) { - markErrorAsHandled(promise); - } - listener.resolve(ret); - } - catch (e) { - listener.reject(e); - } - finally { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - --listener.psd.ref || listener.psd.finalize(); - } - } - function physicalTick() { - usePSD(globalPSD, function () { - beginMicroTickScope() && endMicroTickScope(); - }); - } - function beginMicroTickScope() { - var wasRootExec = isOutsideMicroTick; - isOutsideMicroTick = false; - needsNewPhysicalTick = false; - return wasRootExec; - } - function endMicroTickScope() { - var callbacks, i, l; - do { - while (microtickQueue.length > 0) { - callbacks = microtickQueue; - microtickQueue = []; - l = callbacks.length; - for (i = 0; i < l; ++i) { - var item = callbacks[i]; - item[0].apply(null, item[1]); - } - } - } while (microtickQueue.length > 0); - isOutsideMicroTick = true; - needsNewPhysicalTick = true; - } - function finalizePhysicalTick() { - var unhandledErrs = unhandledErrors; - unhandledErrors = []; - unhandledErrs.forEach(function (p) { - p._PSD.onunhandled.call(null, p._value, p); - }); - var finalizers = tickFinalizers.slice(0); - var i = finalizers.length; - while (i) - finalizers[--i](); - } - function run_at_end_of_this_or_next_physical_tick(fn) { - function finalizer() { - fn(); - tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); - } - tickFinalizers.push(finalizer); - ++numScheduledCalls; - asap(function () { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - function addPossiblyUnhandledError(promise) { - if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) - unhandledErrors.push(promise); - } - function markErrorAsHandled(promise) { - var i = unhandledErrors.length; - while (i) - if (unhandledErrors[--i]._value === promise._value) { - unhandledErrors.splice(i, 1); - return; - } - } - function PromiseReject(reason) { - return new DexiePromise(INTERNAL, false, reason); - } - function wrap(fn, errorCatcher) { - var psd = PSD; - return function () { - var wasRootExec = beginMicroTickScope(), outerScope = PSD; - try { - switchToZone(psd, true); - return fn.apply(this, arguments); - } - catch (e) { - errorCatcher && errorCatcher(e); - } - finally { - switchToZone(outerScope, false); - if (wasRootExec) - endMicroTickScope(); - } - }; - } - var task = { awaits: 0, echoes: 0, id: 0 }; - var taskCounter = 0; - var zoneStack = []; - var zoneEchoes = 0; - var totalEchoes = 0; - var zone_id_counter = 0; - function newScope(fn, props, a1, a2) { - var parent = PSD, psd = Object.create(parent); - psd.parent = parent; - psd.ref = 0; - psd.global = false; - psd.id = ++zone_id_counter; - globalPSD.env; - psd.env = patchGlobalPromise ? { - Promise: DexiePromise, - PromiseProp: { value: DexiePromise, configurable: true, writable: true }, - all: DexiePromise.all, - race: DexiePromise.race, - allSettled: DexiePromise.allSettled, - any: DexiePromise.any, - resolve: DexiePromise.resolve, - reject: DexiePromise.reject, - } : {}; - if (props) - extend(psd, props); - ++parent.ref; - psd.finalize = function () { - --this.parent.ref || this.parent.finalize(); - }; - var rv = usePSD(psd, fn, a1, a2); - if (psd.ref === 0) - psd.finalize(); - return rv; - } - function incrementExpectedAwaits() { - if (!task.id) - task.id = ++taskCounter; - ++task.awaits; - task.echoes += ZONE_ECHO_LIMIT; - return task.id; - } - function decrementExpectedAwaits() { - if (!task.awaits) - return false; - if (--task.awaits === 0) - task.id = 0; - task.echoes = task.awaits * ZONE_ECHO_LIMIT; - return true; - } - if (('' + nativePromiseThen).indexOf('[native code]') === -1) { - incrementExpectedAwaits = decrementExpectedAwaits = nop; - } - function onPossibleParallellAsync(possiblePromise) { - if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { - incrementExpectedAwaits(); - return possiblePromise.then(function (x) { - decrementExpectedAwaits(); - return x; - }, function (e) { - decrementExpectedAwaits(); - return rejection(e); - }); - } - return possiblePromise; - } - function zoneEnterEcho(targetZone) { - ++totalEchoes; - if (!task.echoes || --task.echoes === 0) { - task.echoes = task.awaits = task.id = 0; - } - zoneStack.push(PSD); - switchToZone(targetZone, true); - } - function zoneLeaveEcho() { - var zone = zoneStack[zoneStack.length - 1]; - zoneStack.pop(); - switchToZone(zone, false); - } - function switchToZone(targetZone, bEnteringZone) { - var currentZone = PSD; - if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { - queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); - } - if (targetZone === PSD) - return; - PSD = targetZone; - if (currentZone === globalPSD) - globalPSD.env = snapShot(); - if (patchGlobalPromise) { - var GlobalPromise = globalPSD.env.Promise; - var targetEnv = targetZone.env; - if (currentZone.global || targetZone.global) { - Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); - GlobalPromise.all = targetEnv.all; - GlobalPromise.race = targetEnv.race; - GlobalPromise.resolve = targetEnv.resolve; - GlobalPromise.reject = targetEnv.reject; - if (targetEnv.allSettled) - GlobalPromise.allSettled = targetEnv.allSettled; - if (targetEnv.any) - GlobalPromise.any = targetEnv.any; - } - } - } - function snapShot() { - var GlobalPromise = _global.Promise; - return patchGlobalPromise ? { - Promise: GlobalPromise, - PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), - all: GlobalPromise.all, - race: GlobalPromise.race, - allSettled: GlobalPromise.allSettled, - any: GlobalPromise.any, - resolve: GlobalPromise.resolve, - reject: GlobalPromise.reject, - } : {}; - } - function usePSD(psd, fn, a1, a2, a3) { - var outerScope = PSD; - try { - switchToZone(psd, true); - return fn(a1, a2, a3); - } - finally { - switchToZone(outerScope, false); - } - } - function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { - return typeof fn !== 'function' ? fn : function () { - var outerZone = PSD; - if (possibleAwait) - incrementExpectedAwaits(); - switchToZone(zone, true); - try { - return fn.apply(this, arguments); - } - finally { - switchToZone(outerZone, false); - if (cleanup) - queueMicrotask(decrementExpectedAwaits); - } - }; - } - function execInGlobalContext(cb) { - if (Promise === NativePromise && task.echoes === 0) { - if (zoneEchoes === 0) { - cb(); - } - else { - enqueueNativeMicroTask(cb); - } - } - else { - setTimeout(cb, 0); - } - } - var rejection = DexiePromise.reject; - - function tempTransaction(db, mode, storeNames, fn) { - if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { - if (db._state.openComplete) { - return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); - } - if (!db._state.isBeingOpened) { - if (!db._state.autoOpen) - return rejection(new exceptions.DatabaseClosed()); - db.open().catch(nop); - } - return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); - } - else { - var trans = db._createTransaction(mode, storeNames, db._dbSchema); - try { - trans.create(); - db._state.PR1398_maxLoop = 3; - } - catch (ex) { - if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { - console.warn('Dexie: Need to reopen db'); - db.close({ disableAutoOpen: false }); - return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); - } - return rejection(ex); - } - return trans._promise(mode, function (resolve, reject) { - return newScope(function () { - PSD.trans = trans; - return fn(resolve, reject, trans); - }); - }).then(function (result) { - if (mode === 'readwrite') - try { - trans.idbtrans.commit(); - } - catch (_a) { } - return mode === 'readonly' ? result : trans._completion.then(function () { return result; }); - }); - } - } - - var DEXIE_VERSION = '4.0.4'; - var maxString = String.fromCharCode(65535); - var minKey = -Infinity; - var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; - var STRING_EXPECTED = "String expected."; - var connections = []; - var DBNAMES_DB = '__dbnames'; - var READONLY = 'readonly'; - var READWRITE = 'readwrite'; - - function combine(filter1, filter2) { - return filter1 ? - filter2 ? - function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : - filter1 : - filter2; - } - - var AnyRange = { - type: 3 , - lower: -Infinity, - lowerOpen: false, - upper: [[]], - upperOpen: false - }; - - function workaroundForUndefinedPrimKey(keyPath) { - return typeof keyPath === "string" && !/\./.test(keyPath) - ? function (obj) { - if (obj[keyPath] === undefined && (keyPath in obj)) { - obj = deepClone(obj); - delete obj[keyPath]; - } - return obj; - } - : function (obj) { return obj; }; - } - - function Entity() { - throw exceptions.Type(); - } - - function cmp(a, b) { - try { - var ta = type(a); - var tb = type(b); - if (ta !== tb) { - if (ta === 'Array') - return 1; - if (tb === 'Array') - return -1; - if (ta === 'binary') - return 1; - if (tb === 'binary') - return -1; - if (ta === 'string') - return 1; - if (tb === 'string') - return -1; - if (ta === 'Date') - return 1; - if (tb !== 'Date') - return NaN; - return -1; - } - switch (ta) { - case 'number': - case 'Date': - case 'string': - return a > b ? 1 : a < b ? -1 : 0; - case 'binary': { - return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); - } - case 'Array': - return compareArrays(a, b); - } - } - catch (_a) { } - return NaN; - } - function compareArrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - var res = cmp(a[i], b[i]); - if (res !== 0) - return res; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function compareUint8Arrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - if (a[i] !== b[i]) - return a[i] < b[i] ? -1 : 1; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function type(x) { - var t = typeof x; - if (t !== 'object') - return t; - if (ArrayBuffer.isView(x)) - return 'binary'; - var tsTag = toStringTag(x); - return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; - } - function getUint8Array(a) { - if (a instanceof Uint8Array) - return a; - if (ArrayBuffer.isView(a)) - return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); - return new Uint8Array(a); - } - - var Table = (function () { - function Table() { - } - Table.prototype._trans = function (mode, fn, writeLocked) { - var trans = this._tx || PSD.trans; - var tableName = this.name; - var task = debug && typeof console !== 'undefined' && console.createTask && console.createTask("Dexie: ".concat(mode === 'readonly' ? 'read' : 'write', " ").concat(this.name)); - function checkTableInTransaction(resolve, reject, trans) { - if (!trans.schema[tableName]) - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - return fn(trans.idbtrans, trans); - } - var wasRootExec = beginMicroTickScope(); - try { - var p = trans && trans.db._novip === this.db._novip ? - trans === PSD.trans ? - trans._promise(mode, checkTableInTransaction, writeLocked) : - newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : - tempTransaction(this.db, mode, [this.name], checkTableInTransaction); - if (task) { - p._consoleTask = task; - p = p.catch(function (err) { - console.trace(err); - return rejection(err); - }); - } - return p; - } - finally { - if (wasRootExec) - endMicroTickScope(); - } - }; - Table.prototype.get = function (keyOrCrit, cb) { - var _this = this; - if (keyOrCrit && keyOrCrit.constructor === Object) - return this.where(keyOrCrit).first(cb); - if (keyOrCrit == null) - return rejection(new exceptions.Type("Invalid argument to Table.get()")); - return this._trans('readonly', function (trans) { - return _this.core.get({ trans: trans, key: keyOrCrit }) - .then(function (res) { return _this.hook.reading.fire(res); }); - }).then(cb); - }; - Table.prototype.where = function (indexOrCrit) { - if (typeof indexOrCrit === 'string') - return new this.db.WhereClause(this, indexOrCrit); - if (isArray(indexOrCrit)) - return new this.db.WhereClause(this, "[".concat(indexOrCrit.join('+'), "]")); - var keyPaths = keys(indexOrCrit); - if (keyPaths.length === 1) - return this - .where(keyPaths[0]) - .equals(indexOrCrit[keyPaths[0]]); - var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { - if (ix.compound && - keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { - for (var i = 0; i < keyPaths.length; ++i) { - if (keyPaths.indexOf(ix.keyPath[i]) === -1) - return false; - } - return true; - } - return false; - }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; - if (compoundIndex && this.db._maxKey !== maxString) { - var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); - return this - .where(keyPathsInValidOrder) - .equals(keyPathsInValidOrder.map(function (kp) { return indexOrCrit[kp]; })); - } - if (!compoundIndex && debug) - console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit from a ") + - "compound index [".concat(keyPaths.join('+'), "]")); - var idxByName = this.schema.idxByName; - var idb = this.db._deps.indexedDB; - function equals(a, b) { - return idb.cmp(a, b) === 0; - } - var _a = keyPaths.reduce(function (_a, keyPath) { - var prevIndex = _a[0], prevFilterFn = _a[1]; - var index = idxByName[keyPath]; - var value = indexOrCrit[keyPath]; - return [ - prevIndex || index, - prevIndex || !index ? - combine(prevFilterFn, index && index.multi ? - function (x) { - var prop = getByKeyPath(x, keyPath); - return isArray(prop) && prop.some(function (item) { return equals(value, item); }); - } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) - : prevFilterFn - ]; - }, [null, null]), idx = _a[0], filterFunction = _a[1]; - return idx ? - this.where(idx.name).equals(indexOrCrit[idx.keyPath]) - .filter(filterFunction) : - compoundIndex ? - this.filter(filterFunction) : - this.where(keyPaths).equals(''); - }; - Table.prototype.filter = function (filterFunction) { - return this.toCollection().and(filterFunction); - }; - Table.prototype.count = function (thenShortcut) { - return this.toCollection().count(thenShortcut); - }; - Table.prototype.offset = function (offset) { - return this.toCollection().offset(offset); - }; - Table.prototype.limit = function (numRows) { - return this.toCollection().limit(numRows); - }; - Table.prototype.each = function (callback) { - return this.toCollection().each(callback); - }; - Table.prototype.toArray = function (thenShortcut) { - return this.toCollection().toArray(thenShortcut); - }; - Table.prototype.toCollection = function () { - return new this.db.Collection(new this.db.WhereClause(this)); - }; - Table.prototype.orderBy = function (index) { - return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? - "[".concat(index.join('+'), "]") : - index)); - }; - Table.prototype.reverse = function () { - return this.toCollection().reverse(); - }; - Table.prototype.mapToClass = function (constructor) { - var _a = this, db = _a.db, tableName = _a.name; - this.schema.mappedClass = constructor; - if (constructor.prototype instanceof Entity) { - constructor = (function (_super) { - __extends(class_1, _super); - function class_1() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(class_1.prototype, "db", { - get: function () { return db; }, - enumerable: false, - configurable: true - }); - class_1.prototype.table = function () { return tableName; }; - return class_1; - }(constructor)); - } - var inheritedProps = new Set(); - for (var proto = constructor.prototype; proto; proto = getProto(proto)) { - Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); }); - } - var readHook = function (obj) { - if (!obj) - return obj; - var res = Object.create(constructor.prototype); - for (var m in obj) - if (!inheritedProps.has(m)) - try { - res[m] = obj[m]; - } - catch (_) { } - return res; - }; - if (this.schema.readHook) { - this.hook.reading.unsubscribe(this.schema.readHook); - } - this.schema.readHook = readHook; - this.hook("reading", readHook); - return constructor; - }; - Table.prototype.defineClass = function () { - function Class(content) { - extend(this, content); - } - return this.mapToClass(Class); - }; - Table.prototype.add = function (obj, key) { - var _this = this; - var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans('readwrite', function (trans) { - return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); - }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) - .then(function (lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } - catch (_) { } - } - return lastResult; - }); - }; - Table.prototype.update = function (keyOrObject, modifications) { - if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { - var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); - if (key === undefined) - return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); - return this.where(":id").equals(key).modify(modifications); - } - else { - return this.where(":id").equals(keyOrObject).modify(modifications); - } - }; - Table.prototype.put = function (obj, key) { - var _this = this; - var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) - .then(function (lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } - catch (_) { } - } - return lastResult; - }); - }; - Table.prototype.delete = function (key) { - var _this = this; - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); - }; - Table.prototype.clear = function () { - var _this = this; - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); - }; - Table.prototype.bulkGet = function (keys) { - var _this = this; - return this._trans('readonly', function (trans) { - return _this.core.getMany({ - keys: keys, - trans: trans - }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); - }); - }; - Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { - var _this = this; - var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; - options = options || (keys ? undefined : keysOrOptions); - var wantResults = options ? options.allKeys : undefined; - return this._trans('readwrite', function (trans) { - var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - if (keyPath && keys) - throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); - if (keys && keys.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToAdd = keyPath && auto ? - objects.map(workaroundForUndefinedPrimKey(keyPath)) : - objects; - return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, wantResults: wantResults }) - .then(function (_a) { - var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table.prototype.bulkPut = function (objects, keysOrOptions, options) { - var _this = this; - var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; - options = options || (keys ? undefined : keysOrOptions); - var wantResults = options ? options.allKeys : undefined; - return this._trans('readwrite', function (trans) { - var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - if (keyPath && keys) - throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); - if (keys && keys.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToPut = keyPath && auto ? - objects.map(workaroundForUndefinedPrimKey(keyPath)) : - objects; - return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, wantResults: wantResults }) - .then(function (_a) { - var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table.prototype.bulkUpdate = function (keysAndChanges) { - var _this = this; - var coreTable = this.core; - var keys = keysAndChanges.map(function (entry) { return entry.key; }); - var changeSpecs = keysAndChanges.map(function (entry) { return entry.changes; }); - var offsetMap = []; - return this._trans('readwrite', function (trans) { - return coreTable.getMany({ trans: trans, keys: keys, cache: 'clone' }).then(function (objs) { - var resultKeys = []; - var resultObjs = []; - keysAndChanges.forEach(function (_a, idx) { - var key = _a.key, changes = _a.changes; - var obj = objs[idx]; - if (obj) { - for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { - var keyPath = _b[_i]; - var value = changes[keyPath]; - if (keyPath === _this.schema.primKey.keyPath) { - if (cmp(value, key) !== 0) { - throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); - } - } - else { - setByKeyPath(obj, keyPath, value); - } - } - offsetMap.push(idx); - resultKeys.push(key); - resultObjs.push(obj); - } - }); - var numEntries = resultKeys.length; - return coreTable - .mutate({ - trans: trans, - type: 'put', - keys: resultKeys, - values: resultObjs, - updates: { - keys: keys, - changeSpecs: changeSpecs - } - }) - .then(function (_a) { - var numFailures = _a.numFailures, failures = _a.failures; - if (numFailures === 0) - return numEntries; - for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { - var offset = _b[_i]; - var mappedOffset = offsetMap[Number(offset)]; - if (mappedOffset != null) { - var failure = failures[offset]; - delete failures[offset]; - failures[mappedOffset] = failure; - } - } - throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); - }); - }); - }); - }; - Table.prototype.bulkDelete = function (keys) { - var _this = this; - var numKeys = keys.length; - return this._trans('readwrite', function (trans) { - return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); - }).then(function (_a) { - var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; - if (numFailures === 0) - return lastResult; - throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); - }); - }; - return Table; - }()); - - function Events(ctx) { - var evs = {}; - var rv = function (eventName, subscriber) { - if (subscriber) { - var i = arguments.length, args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - evs[eventName].subscribe.apply(null, args); - return ctx; - } - else if (typeof (eventName) === 'string') { - return evs[eventName]; - } - }; - rv.addEventType = add; - for (var i = 1, l = arguments.length; i < l; ++i) { - add(arguments[i]); - } - return rv; - function add(eventName, chainFunction, defaultFunction) { - if (typeof eventName === 'object') - return addConfiguredEvents(eventName); - if (!chainFunction) - chainFunction = reverseStoppableEventChain; - if (!defaultFunction) - defaultFunction = nop; - var context = { - subscribers: [], - fire: defaultFunction, - subscribe: function (cb) { - if (context.subscribers.indexOf(cb) === -1) { - context.subscribers.push(cb); - context.fire = chainFunction(context.fire, cb); - } - }, - unsubscribe: function (cb) { - context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); - context.fire = context.subscribers.reduce(chainFunction, defaultFunction); - } - }; - evs[eventName] = rv[eventName] = context; - return context; - } - function addConfiguredEvents(cfg) { - keys(cfg).forEach(function (eventName) { - var args = cfg[eventName]; - if (isArray(args)) { - add(eventName, cfg[eventName][0], cfg[eventName][1]); - } - else if (args === 'asap') { - var context = add(eventName, mirror, function fire() { - var i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - context.subscribers.forEach(function (fn) { - asap$1(function fireEvent() { - fn.apply(null, args); - }); - }); - }); - } - else - throw new exceptions.InvalidArgument("Invalid event config"); - }); - } - } - - function makeClassConstructor(prototype, constructor) { - derive(constructor).from({ prototype: prototype }); - return constructor; - } - - function createTableConstructor(db) { - return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) { - this.db = db; - this._tx = trans; - this.name = name; - this.schema = tableSchema; - this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { - "creating": [hookCreatingChain, nop], - "reading": [pureFunctionChain, mirror], - "updating": [hookUpdatingChain, nop], - "deleting": [hookDeletingChain, nop] - }); - }); - } - - function isPlainKeyRange(ctx, ignoreLimitFilter) { - return !(ctx.filter || ctx.algorithm || ctx.or) && - (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); - } - function addFilter(ctx, fn) { - ctx.filter = combine(ctx.filter, fn); - } - function addReplayFilter(ctx, factory, isLimitFilter) { - var curr = ctx.replayFilter; - ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; - ctx.justLimit = isLimitFilter && !curr; - } - function addMatchFilter(ctx, fn) { - ctx.isMatch = combine(ctx.isMatch, fn); - } - function getIndexOrStore(ctx, coreSchema) { - if (ctx.isPrimKey) - return coreSchema.primaryKey; - var index = coreSchema.getIndexByKeyPath(ctx.index); - if (!index) - throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); - return index; - } - function openCursor(ctx, coreTable, trans) { - var index = getIndexOrStore(ctx, coreTable.schema); - return coreTable.openCursor({ - trans: trans, - values: !ctx.keysOnly, - reverse: ctx.dir === 'prev', - unique: !!ctx.unique, - query: { - index: index, - range: ctx.range - } - }); - } - function iter(ctx, fn, coreTrans, coreTable) { - var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; - if (!ctx.or) { - return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); - } - else { - var set_1 = {}; - var union = function (item, cursor, advance) { - if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { - var primaryKey = cursor.primaryKey; - var key = '' + primaryKey; - if (key === '[object ArrayBuffer]') - key = '' + new Uint8Array(primaryKey); - if (!hasOwn(set_1, key)) { - set_1[key] = true; - fn(item, cursor, advance); - } - } - }; - return Promise.all([ - ctx.or._iterate(union, coreTrans), - iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) - ]); - } - } - function iterate(cursorPromise, filter, fn, valueMapper) { - var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; - var wrappedFn = wrap(mappedFn); - return cursorPromise.then(function (cursor) { - if (cursor) { - return cursor.start(function () { - var c = function () { return cursor.continue(); }; - if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) - wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); - c(); - }); - } - }); - } - - var PropModSymbol = Symbol(); - var PropModification = (function () { - function PropModification(spec) { - Object.assign(this, spec); - } - PropModification.prototype.execute = function (value) { - var _a; - var prefixToReplace = (_a = this.replacePrefix) === null || _a === void 0 ? void 0 : _a[0]; - if (prefixToReplace && typeof value === 'string' && value.startsWith(prefixToReplace)) { - return this.replacePrefix[1] + value.substring(prefixToReplace.length); - } - return value; - }; - return PropModification; - }()); - - var Collection = (function () { - function Collection() { - } - Collection.prototype._read = function (fn, cb) { - var ctx = this._ctx; - return ctx.error ? - ctx.table._trans(null, rejection.bind(null, ctx.error)) : - ctx.table._trans('readonly', fn).then(cb); - }; - Collection.prototype._write = function (fn) { - var ctx = this._ctx; - return ctx.error ? - ctx.table._trans(null, rejection.bind(null, ctx.error)) : - ctx.table._trans('readwrite', fn, "locked"); - }; - Collection.prototype._addAlgorithm = function (fn) { - var ctx = this._ctx; - ctx.algorithm = combine(ctx.algorithm, fn); - }; - Collection.prototype._iterate = function (fn, coreTrans) { - return iter(this._ctx, fn, coreTrans, this._ctx.table.core); - }; - Collection.prototype.clone = function (props) { - var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); - if (props) - extend(ctx, props); - rv._ctx = ctx; - return rv; - }; - Collection.prototype.raw = function () { - this._ctx.valueMapper = null; - return this; - }; - Collection.prototype.each = function (fn) { - var ctx = this._ctx; - return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); - }; - Collection.prototype.count = function (cb) { - var _this = this; - return this._read(function (trans) { - var ctx = _this._ctx; - var coreTable = ctx.table.core; - if (isPlainKeyRange(ctx, true)) { - return coreTable.count({ - trans: trans, - query: { - index: getIndexOrStore(ctx, coreTable.schema), - range: ctx.range - } - }).then(function (count) { return Math.min(count, ctx.limit); }); - } - else { - var count = 0; - return iter(ctx, function () { ++count; return false; }, trans, coreTable) - .then(function () { return count; }); - } - }).then(cb); - }; - Collection.prototype.sortBy = function (keyPath, cb) { - var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; - function getval(obj, i) { - if (i) - return getval(obj[parts[i]], i - 1); - return obj[lastPart]; - } - var order = this._ctx.dir === "next" ? 1 : -1; - function sorter(a, b) { - var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); - return aVal < bVal ? -order : aVal > bVal ? order : 0; - } - return this.toArray(function (a) { - return a.sort(sorter); - }).then(cb); - }; - Collection.prototype.toArray = function (cb) { - var _this = this; - return this._read(function (trans) { - var ctx = _this._ctx; - if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { - var valueMapper_1 = ctx.valueMapper; - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans: trans, - limit: ctx.limit, - values: true, - query: { - index: index, - range: ctx.range - } - }).then(function (_a) { - var result = _a.result; - return valueMapper_1 ? result.map(valueMapper_1) : result; - }); - } - else { - var a_1 = []; - return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); - } - }, cb); - }; - Collection.prototype.offset = function (offset) { - var ctx = this._ctx; - if (offset <= 0) - return this; - ctx.offset += offset; - if (isPlainKeyRange(ctx)) { - addReplayFilter(ctx, function () { - var offsetLeft = offset; - return function (cursor, advance) { - if (offsetLeft === 0) - return true; - if (offsetLeft === 1) { - --offsetLeft; - return false; - } - advance(function () { - cursor.advance(offsetLeft); - offsetLeft = 0; - }); - return false; - }; - }); - } - else { - addReplayFilter(ctx, function () { - var offsetLeft = offset; - return function () { return (--offsetLeft < 0); }; - }); - } - return this; - }; - Collection.prototype.limit = function (numRows) { - this._ctx.limit = Math.min(this._ctx.limit, numRows); - addReplayFilter(this._ctx, function () { - var rowsLeft = numRows; - return function (cursor, advance, resolve) { - if (--rowsLeft <= 0) - advance(resolve); - return rowsLeft >= 0; - }; - }, true); - return this; - }; - Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { - addFilter(this._ctx, function (cursor, advance, resolve) { - if (filterFunction(cursor.value)) { - advance(resolve); - return bIncludeStopEntry; - } - else { - return true; - } - }); - return this; - }; - Collection.prototype.first = function (cb) { - return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); - }; - Collection.prototype.last = function (cb) { - return this.reverse().first(cb); - }; - Collection.prototype.filter = function (filterFunction) { - addFilter(this._ctx, function (cursor) { - return filterFunction(cursor.value); - }); - addMatchFilter(this._ctx, filterFunction); - return this; - }; - Collection.prototype.and = function (filter) { - return this.filter(filter); - }; - Collection.prototype.or = function (indexName) { - return new this.db.WhereClause(this._ctx.table, indexName, this); - }; - Collection.prototype.reverse = function () { - this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); - if (this._ondirectionchange) - this._ondirectionchange(this._ctx.dir); - return this; - }; - Collection.prototype.desc = function () { - return this.reverse(); - }; - Collection.prototype.eachKey = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function (val, cursor) { cb(cursor.key, cursor); }); - }; - Collection.prototype.eachUniqueKey = function (cb) { - this._ctx.unique = "unique"; - return this.eachKey(cb); - }; - Collection.prototype.eachPrimaryKey = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); - }; - Collection.prototype.keys = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function (item, cursor) { - a.push(cursor.key); - }).then(function () { - return a; - }).then(cb); - }; - Collection.prototype.primaryKeys = function (cb) { - var ctx = this._ctx; - if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { - return this._read(function (trans) { - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans: trans, - values: false, - limit: ctx.limit, - query: { - index: index, - range: ctx.range - } - }); - }).then(function (_a) { - var result = _a.result; - return result; - }).then(cb); - } - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function (item, cursor) { - a.push(cursor.primaryKey); - }).then(function () { - return a; - }).then(cb); - }; - Collection.prototype.uniqueKeys = function (cb) { - this._ctx.unique = "unique"; - return this.keys(cb); - }; - Collection.prototype.firstKey = function (cb) { - return this.limit(1).keys(function (a) { return a[0]; }).then(cb); - }; - Collection.prototype.lastKey = function (cb) { - return this.reverse().firstKey(cb); - }; - Collection.prototype.distinct = function () { - var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; - if (!idx || !idx.multi) - return this; - var set = {}; - addFilter(this._ctx, function (cursor) { - var strKey = cursor.primaryKey.toString(); - var found = hasOwn(set, strKey); - set[strKey] = true; - return !found; - }); - return this; - }; - Collection.prototype.modify = function (changes) { - var _this = this; - var ctx = this._ctx; - return this._write(function (trans) { - var modifyer; - if (typeof changes === 'function') { - modifyer = changes; - } - else { - var keyPaths = keys(changes); - var numKeys = keyPaths.length; - modifyer = function (item) { - var anythingModified = false; - for (var i = 0; i < numKeys; ++i) { - var keyPath = keyPaths[i]; - var val = changes[keyPath]; - var origVal = getByKeyPath(item, keyPath); - if (val instanceof PropModification) { - setByKeyPath(item, keyPath, val.execute(origVal)); - anythingModified = true; - } - else if (origVal !== val) { - setByKeyPath(item, keyPath, val); - anythingModified = true; - } - } - return anythingModified; - }; - } - var coreTable = ctx.table.core; - var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; - var limit = _this.db._options.modifyChunkSize || 200; - var totalFailures = []; - var successCount = 0; - var failedKeys = []; - var applyMutateResult = function (expectedCount, res) { - var failures = res.failures, numFailures = res.numFailures; - successCount += expectedCount - numFailures; - for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { - var pos = _a[_i]; - totalFailures.push(failures[pos]); - } - }; - return _this.clone().primaryKeys().then(function (keys) { - var nextChunk = function (offset) { - var count = Math.min(limit, keys.length - offset); - return coreTable.getMany({ - trans: trans, - keys: keys.slice(offset, offset + count), - cache: "immutable" - }).then(function (values) { - var addValues = []; - var putValues = []; - var putKeys = outbound ? [] : null; - var deleteKeys = []; - for (var i = 0; i < count; ++i) { - var origValue = values[i]; - var ctx_1 = { - value: deepClone(origValue), - primKey: keys[offset + i] - }; - if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { - if (ctx_1.value == null) { - deleteKeys.push(keys[offset + i]); - } - else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { - deleteKeys.push(keys[offset + i]); - addValues.push(ctx_1.value); - } - else { - putValues.push(ctx_1.value); - if (outbound) - putKeys.push(keys[offset + i]); - } - } - } - var criteria = isPlainKeyRange(ctx) && - ctx.limit === Infinity && - (typeof changes !== 'function' || changes === deleteCallback) && { - index: ctx.index, - range: ctx.range - }; - return Promise.resolve(addValues.length > 0 && - coreTable.mutate({ trans: trans, type: 'add', values: addValues }) - .then(function (res) { - for (var pos in res.failures) { - deleteKeys.splice(parseInt(pos), 1); - } - applyMutateResult(addValues.length, res); - })).then(function () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && - coreTable.mutate({ - trans: trans, - type: 'put', - keys: putKeys, - values: putValues, - criteria: criteria, - changeSpec: typeof changes !== 'function' - && changes - }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && - coreTable.mutate({ - trans: trans, - type: 'delete', - keys: deleteKeys, - criteria: criteria - }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { - return keys.length > offset + count && nextChunk(offset + limit); - }); - }); - }; - return nextChunk(0).then(function () { - if (totalFailures.length > 0) - throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); - return keys.length; - }); - }); - }); - }; - Collection.prototype.delete = function () { - var ctx = this._ctx, range = ctx.range; - if (isPlainKeyRange(ctx) && - (ctx.isPrimKey || range.type === 3 )) - { - return this._write(function (trans) { - var primaryKey = ctx.table.core.schema.primaryKey; - var coreRange = range; - return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { - return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) - .then(function (_a) { - var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures; - if (numFailures) - throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); - return count - numFailures; - }); - }); - }); - } - return this.modify(deleteCallback); - }; - return Collection; - }()); - var deleteCallback = function (value, ctx) { return ctx.value = null; }; - - function createCollectionConstructor(db) { - return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { - this.db = db; - var keyRange = AnyRange, error = null; - if (keyRangeGenerator) - try { - keyRange = keyRangeGenerator(); - } - catch (ex) { - error = ex; - } - var whereCtx = whereClause._ctx; - var table = whereCtx.table; - var readingHook = table.hook.reading.fire; - this._ctx = { - table: table, - index: whereCtx.index, - isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), - range: keyRange, - keysOnly: false, - dir: "next", - unique: "", - algorithm: null, - filter: null, - replayFilter: null, - justLimit: true, - isMatch: null, - offset: 0, - limit: Infinity, - error: error, - or: whereCtx.or, - valueMapper: readingHook !== mirror ? readingHook : null - }; - }); - } - - function simpleCompare(a, b) { - return a < b ? -1 : a === b ? 0 : 1; - } - function simpleCompareReverse(a, b) { - return a > b ? -1 : a === b ? 0 : 1; - } - - function fail(collectionOrWhereClause, err, T) { - var collection = collectionOrWhereClause instanceof WhereClause ? - new collectionOrWhereClause.Collection(collectionOrWhereClause) : - collectionOrWhereClause; - collection._ctx.error = T ? new T(err) : new TypeError(err); - return collection; - } - function emptyCollection(whereClause) { - return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).limit(0); - } - function upperFactory(dir) { - return dir === "next" ? - function (s) { return s.toUpperCase(); } : - function (s) { return s.toLowerCase(); }; - } - function lowerFactory(dir) { - return dir === "next" ? - function (s) { return s.toLowerCase(); } : - function (s) { return s.toUpperCase(); }; - } - function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { - var length = Math.min(key.length, lowerNeedle.length); - var llp = -1; - for (var i = 0; i < length; ++i) { - var lwrKeyChar = lowerKey[i]; - if (lwrKeyChar !== lowerNeedle[i]) { - if (cmp(key[i], upperNeedle[i]) < 0) - return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); - if (cmp(key[i], lowerNeedle[i]) < 0) - return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); - if (llp >= 0) - return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); - return null; - } - if (cmp(key[i], lwrKeyChar) < 0) - llp = i; - } - if (length < lowerNeedle.length && dir === "next") - return key + upperNeedle.substr(key.length); - if (length < key.length && dir === "prev") - return key.substr(0, upperNeedle.length); - return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); - } - function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { - var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; - if (!needles.every(function (s) { return typeof s === 'string'; })) { - return fail(whereClause, STRING_EXPECTED); - } - function initDirection(dir) { - upper = upperFactory(dir); - lower = lowerFactory(dir); - compare = (dir === "next" ? simpleCompare : simpleCompareReverse); - var needleBounds = needles.map(function (needle) { - return { lower: lower(needle), upper: upper(needle) }; - }).sort(function (a, b) { - return compare(a.lower, b.lower); - }); - upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); - lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); - direction = dir; - nextKeySuffix = (dir === "next" ? "" : suffix); - } - initDirection("next"); - var c = new whereClause.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); - c._ondirectionchange = function (direction) { - initDirection(direction); - }; - var firstPossibleNeedle = 0; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - if (typeof key !== 'string') - return false; - var lowerKey = lower(key); - if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { - return true; - } - else { - var lowestPossibleCasing = null; - for (var i = firstPossibleNeedle; i < needlesLen; ++i) { - var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); - if (casing === null && lowestPossibleCasing === null) - firstPossibleNeedle = i + 1; - else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { - lowestPossibleCasing = casing; - } - } - if (lowestPossibleCasing !== null) { - advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); - } - else { - advance(resolve); - } - return false; - } - }); - return c; - } - function createRange(lower, upper, lowerOpen, upperOpen) { - return { - type: 2 , - lower: lower, - upper: upper, - lowerOpen: lowerOpen, - upperOpen: upperOpen - }; - } - function rangeEqual(value) { - return { - type: 1 , - lower: value, - upper: value - }; - } - - var WhereClause = (function () { - function WhereClause() { - } - Object.defineProperty(WhereClause.prototype, "Collection", { - get: function () { - return this._ctx.table.db.Collection; - }, - enumerable: false, - configurable: true - }); - WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { - includeLower = includeLower !== false; - includeUpper = includeUpper === true; - try { - if ((this._cmp(lower, upper) > 0) || - (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) - return emptyCollection(this); - return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - }; - WhereClause.prototype.equals = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return rangeEqual(value); }); - }; - WhereClause.prototype.above = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(value, undefined, true); }); - }; - WhereClause.prototype.aboveOrEqual = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(value, undefined, false); }); - }; - WhereClause.prototype.below = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); - }; - WhereClause.prototype.belowOrEqual = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(undefined, value); }); - }; - WhereClause.prototype.startsWith = function (str) { - if (typeof str !== 'string') - return fail(this, STRING_EXPECTED); - return this.between(str, str + maxString, true, true); - }; - WhereClause.prototype.startsWithIgnoreCase = function (str) { - if (str === "") - return this.startsWith(str); - return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); - }; - WhereClause.prototype.equalsIgnoreCase = function (str) { - return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); - }; - WhereClause.prototype.anyOfIgnoreCase = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); - }; - WhereClause.prototype.startsWithAnyOfIgnoreCase = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function (n) { return x.indexOf(n) === 0; }); }, set, maxString); - }; - WhereClause.prototype.anyOf = function () { - var _this = this; - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - var compare = this._cmp; - try { - set.sort(compare); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - if (set.length === 0) - return emptyCollection(this); - var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); - c._ondirectionchange = function (direction) { - compare = (direction === "next" ? - _this._ascending : - _this._descending); - set.sort(compare); - }; - var i = 0; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - while (compare(key, set[i]) > 0) { - ++i; - if (i === set.length) { - advance(resolve); - return false; - } - } - if (compare(key, set[i]) === 0) { - return true; - } - else { - advance(function () { cursor.continue(set[i]); }); - return false; - } - }); - return c; - }; - WhereClause.prototype.notEqual = function (value) { - return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); - }; - WhereClause.prototype.noneOf = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return new this.Collection(this); - try { - set.sort(this._ascending); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var ranges = set.reduce(function (res, val) { return res ? - res.concat([[res[res.length - 1][1], val]]) : - [[minKey, val]]; }, null); - ranges.push([set[set.length - 1], this.db._maxKey]); - return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); - }; - WhereClause.prototype.inAnyRange = function (ranges, options) { - var _this = this; - var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; - if (ranges.length === 0) - return emptyCollection(this); - if (!ranges.every(function (range) { - return range[0] !== undefined && - range[1] !== undefined && - ascending(range[0], range[1]) <= 0; - })) { - return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); - } - var includeLowers = !options || options.includeLowers !== false; - var includeUppers = options && options.includeUppers === true; - function addRange(ranges, newRange) { - var i = 0, l = ranges.length; - for (; i < l; ++i) { - var range = ranges[i]; - if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { - range[0] = min(range[0], newRange[0]); - range[1] = max(range[1], newRange[1]); - break; - } - } - if (i === l) - ranges.push(newRange); - return ranges; - } - var sortDirection = ascending; - function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } - var set; - try { - set = ranges.reduce(addRange, []); - set.sort(rangeSorter); - } - catch (ex) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var rangePos = 0; - var keyIsBeyondCurrentEntry = includeUppers ? - function (key) { return ascending(key, set[rangePos][1]) > 0; } : - function (key) { return ascending(key, set[rangePos][1]) >= 0; }; - var keyIsBeforeCurrentEntry = includeLowers ? - function (key) { return descending(key, set[rangePos][0]) > 0; } : - function (key) { return descending(key, set[rangePos][0]) >= 0; }; - function keyWithinCurrentRange(key) { - return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); - } - var checkKey = keyIsBeyondCurrentEntry; - var c = new this.Collection(this, function () { return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); }); - c._ondirectionchange = function (direction) { - if (direction === "next") { - checkKey = keyIsBeyondCurrentEntry; - sortDirection = ascending; - } - else { - checkKey = keyIsBeforeCurrentEntry; - sortDirection = descending; - } - set.sort(rangeSorter); - }; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - while (checkKey(key)) { - ++rangePos; - if (rangePos === set.length) { - advance(resolve); - return false; - } - } - if (keyWithinCurrentRange(key)) { - return true; - } - else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { - return false; - } - else { - advance(function () { - if (sortDirection === ascending) - cursor.continue(set[rangePos][0]); - else - cursor.continue(set[rangePos][1]); - }); - return false; - } - }); - return c; - }; - WhereClause.prototype.startsWithAnyOf = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (!set.every(function (s) { return typeof s === 'string'; })) { - return fail(this, "startsWithAnyOf() only works with strings"); - } - if (set.length === 0) - return emptyCollection(this); - return this.inAnyRange(set.map(function (str) { return [str, str + maxString]; })); - }; - return WhereClause; - }()); - - function createWhereClauseConstructor(db) { - return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { - this.db = db; - this._ctx = { - table: table, - index: index === ":id" ? null : index, - or: orCollection - }; - this._cmp = this._ascending = cmp; - this._descending = function (a, b) { return cmp(b, a); }; - this._max = function (a, b) { return cmp(a, b) > 0 ? a : b; }; - this._min = function (a, b) { return cmp(a, b) < 0 ? a : b; }; - this._IDBKeyRange = db._deps.IDBKeyRange; - if (!this._IDBKeyRange) - throw new exceptions.MissingAPI(); - }); - } - - function eventRejectHandler(reject) { - return wrap(function (event) { - preventDefault(event); - reject(event.target.error); - return false; - }); - } - function preventDefault(event) { - if (event.stopPropagation) - event.stopPropagation(); - if (event.preventDefault) - event.preventDefault(); - } - - var DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; - var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; - var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); - - var Transaction = (function () { - function Transaction() { - } - Transaction.prototype._lock = function () { - assert(!PSD.global); - ++this._reculock; - if (this._reculock === 1 && !PSD.global) - PSD.lockOwnerFor = this; - return this; - }; - Transaction.prototype._unlock = function () { - assert(!PSD.global); - if (--this._reculock === 0) { - if (!PSD.global) - PSD.lockOwnerFor = null; - while (this._blockedFuncs.length > 0 && !this._locked()) { - var fnAndPSD = this._blockedFuncs.shift(); - try { - usePSD(fnAndPSD[1], fnAndPSD[0]); - } - catch (e) { } - } - } - return this; - }; - Transaction.prototype._locked = function () { - return this._reculock && PSD.lockOwnerFor !== this; - }; - Transaction.prototype.create = function (idbtrans) { - var _this = this; - if (!this.mode) - return this; - var idbdb = this.db.idbdb; - var dbOpenError = this.db._state.dbOpenError; - assert(!this.idbtrans); - if (!idbtrans && !idbdb) { - switch (dbOpenError && dbOpenError.name) { - case "DatabaseClosedError": - throw new exceptions.DatabaseClosed(dbOpenError); - case "MissingAPIError": - throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); - default: - throw new exceptions.OpenFailed(dbOpenError); - } - } - if (!this.active) - throw new exceptions.TransactionInactive(); - assert(this._completion._state === null); - idbtrans = this.idbtrans = idbtrans || - (this.db.core - ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) - : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); - idbtrans.onerror = wrap(function (ev) { - preventDefault(ev); - _this._reject(idbtrans.error); - }); - idbtrans.onabort = wrap(function (ev) { - preventDefault(ev); - _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); - _this.active = false; - _this.on("abort").fire(ev); - }); - idbtrans.oncomplete = wrap(function () { - _this.active = false; - _this._resolve(); - if ('mutatedParts' in idbtrans) { - globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); - } - }); - return this; - }; - Transaction.prototype._promise = function (mode, fn, bWriteLock) { - var _this = this; - if (mode === 'readwrite' && this.mode !== 'readwrite') - return rejection(new exceptions.ReadOnly("Transaction is readonly")); - if (!this.active) - return rejection(new exceptions.TransactionInactive()); - if (this._locked()) { - return new DexiePromise(function (resolve, reject) { - _this._blockedFuncs.push([function () { - _this._promise(mode, fn, bWriteLock).then(resolve, reject); - }, PSD]); - }); - } - else if (bWriteLock) { - return newScope(function () { - var p = new DexiePromise(function (resolve, reject) { - _this._lock(); - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p.finally(function () { return _this._unlock(); }); - p._lib = true; - return p; - }); - } - else { - var p = new DexiePromise(function (resolve, reject) { - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p._lib = true; - return p; - } - }; - Transaction.prototype._root = function () { - return this.parent ? this.parent._root() : this; - }; - Transaction.prototype.waitFor = function (promiseLike) { - var root = this._root(); - var promise = DexiePromise.resolve(promiseLike); - if (root._waitingFor) { - root._waitingFor = root._waitingFor.then(function () { return promise; }); - } - else { - root._waitingFor = promise; - root._waitingQueue = []; - var store = root.idbtrans.objectStore(root.storeNames[0]); - (function spin() { - ++root._spinCount; - while (root._waitingQueue.length) - (root._waitingQueue.shift())(); - if (root._waitingFor) - store.get(-Infinity).onsuccess = spin; - }()); - } - var currentWaitPromise = root._waitingFor; - return new DexiePromise(function (resolve, reject) { - promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { - if (root._waitingFor === currentWaitPromise) { - root._waitingFor = null; - } - }); - }); - }; - Transaction.prototype.abort = function () { - if (this.active) { - this.active = false; - if (this.idbtrans) - this.idbtrans.abort(); - this._reject(new exceptions.Abort()); - } - }; - Transaction.prototype.table = function (tableName) { - var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); - if (hasOwn(memoizedTables, tableName)) - return memoizedTables[tableName]; - var tableSchema = this.schema[tableName]; - if (!tableSchema) { - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - } - var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); - transactionBoundTable.core = this.db.core.table(tableName); - memoizedTables[tableName] = transactionBoundTable; - return transactionBoundTable; - }; - return Transaction; - }()); - - function createTransactionConstructor(db) { - return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { - var _this = this; - this.db = db; - this.mode = mode; - this.storeNames = storeNames; - this.schema = dbschema; - this.chromeTransactionDurability = chromeTransactionDurability; - this.idbtrans = null; - this.on = Events(this, "complete", "error", "abort"); - this.parent = parent || null; - this.active = true; - this._reculock = 0; - this._blockedFuncs = []; - this._resolve = null; - this._reject = null; - this._waitingFor = null; - this._waitingQueue = null; - this._spinCount = 0; - this._completion = new DexiePromise(function (resolve, reject) { - _this._resolve = resolve; - _this._reject = reject; - }); - this._completion.then(function () { - _this.active = false; - _this.on.complete.fire(); - }, function (e) { - var wasActive = _this.active; - _this.active = false; - _this.on.error.fire(e); - _this.parent ? - _this.parent._reject(e) : - wasActive && _this.idbtrans && _this.idbtrans.abort(); - return rejection(e); - }); - }); - } - - function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { - return { - name: name, - keyPath: keyPath, - unique: unique, - multi: multi, - auto: auto, - compound: compound, - src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) - }; - } - function nameFromKeyPath(keyPath) { - return typeof keyPath === 'string' ? - keyPath : - keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; - } - - function createTableSchema(name, primKey, indexes) { - return { - name: name, - primKey: primKey, - indexes: indexes, - mappedClass: null, - idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) - }; - } - - function safariMultiStoreFix(storeNames) { - return storeNames.length === 1 ? storeNames[0] : storeNames; - } - var getMaxKey = function (IdbKeyRange) { - try { - IdbKeyRange.only([[]]); - getMaxKey = function () { return [[]]; }; - return [[]]; - } - catch (e) { - getMaxKey = function () { return maxString; }; - return maxString; - } - }; - - function getKeyExtractor(keyPath) { - if (keyPath == null) { - return function () { return undefined; }; - } - else if (typeof keyPath === 'string') { - return getSinglePathKeyExtractor(keyPath); - } - else { - return function (obj) { return getByKeyPath(obj, keyPath); }; - } - } - function getSinglePathKeyExtractor(keyPath) { - var split = keyPath.split('.'); - if (split.length === 1) { - return function (obj) { return obj[keyPath]; }; - } - else { - return function (obj) { return getByKeyPath(obj, keyPath); }; - } - } - - function arrayify(arrayLike) { - return [].slice.call(arrayLike); - } - var _id_counter = 0; - function getKeyPathAlias(keyPath) { - return keyPath == null ? - ":id" : - typeof keyPath === 'string' ? - keyPath : - "[".concat(keyPath.join('+'), "]"); - } - function createDBCore(db, IdbKeyRange, tmpTrans) { - function extractSchema(db, trans) { - var tables = arrayify(db.objectStoreNames); - return { - schema: { - name: db.name, - tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { - var keyPath = store.keyPath, autoIncrement = store.autoIncrement; - var compound = isArray(keyPath); - var outbound = keyPath == null; - var indexByKeyPath = {}; - var result = { - name: store.name, - primaryKey: { - name: null, - isPrimaryKey: true, - outbound: outbound, - compound: compound, - keyPath: keyPath, - autoIncrement: autoIncrement, - unique: true, - extractKey: getKeyExtractor(keyPath) - }, - indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) - .map(function (index) { - var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; - var compound = isArray(keyPath); - var result = { - name: name, - compound: compound, - keyPath: keyPath, - unique: unique, - multiEntry: multiEntry, - extractKey: getKeyExtractor(keyPath) - }; - indexByKeyPath[getKeyPathAlias(keyPath)] = result; - return result; - }), - getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } - }; - indexByKeyPath[":id"] = result.primaryKey; - if (keyPath != null) { - indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; - } - return result; - }) - }, - hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && - !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && - !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && - [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) - }; - } - function makeIDBKeyRange(range) { - if (range.type === 3 ) - return null; - if (range.type === 4 ) - throw new Error("Cannot convert never type to IDBKeyRange"); - var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; - var idbRange = lower === undefined ? - upper === undefined ? - null : - IdbKeyRange.upperBound(upper, !!upperOpen) : - upper === undefined ? - IdbKeyRange.lowerBound(lower, !!lowerOpen) : - IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); - return idbRange; - } - function createDbCoreTable(tableSchema) { - var tableName = tableSchema.name; - function mutate(_a) { - var trans = _a.trans, type = _a.type, keys = _a.keys, values = _a.values, range = _a.range; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var outbound = store.keyPath == null; - var isAddOrPut = type === "put" || type === "add"; - if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') - throw new Error("Invalid operation type: " + type); - var length = (keys || values || { length: 1 }).length; - if (keys && values && keys.length !== values.length) { - throw new Error("Given keys array must have same length as given values array."); - } - if (length === 0) - return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); - var req; - var reqs = []; - var failures = []; - var numFailures = 0; - var errorHandler = function (event) { - ++numFailures; - preventDefault(event); - }; - if (type === 'deleteRange') { - if (range.type === 4 ) - return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); - if (range.type === 3 ) - reqs.push(req = store.clear()); - else - reqs.push(req = store.delete(makeIDBKeyRange(range))); - } - else { - var _a = isAddOrPut ? - outbound ? - [values, keys] : - [values, null] : - [keys, null], args1 = _a[0], args2 = _a[1]; - if (isAddOrPut) { - for (var i = 0; i < length; ++i) { - reqs.push(req = (args2 && args2[i] !== undefined ? - store[type](args1[i], args2[i]) : - store[type](args1[i]))); - req.onerror = errorHandler; - } - } - else { - for (var i = 0; i < length; ++i) { - reqs.push(req = store[type](args1[i])); - req.onerror = errorHandler; - } - } - } - var done = function (event) { - var lastResult = event.target.result; - reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); - resolve({ - numFailures: numFailures, - failures: failures, - results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), - lastResult: lastResult - }); - }; - req.onerror = function (event) { - errorHandler(event); - done(event); - }; - req.onsuccess = done; - }); - } - function openCursor(_a) { - var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var index = query.index, range = query.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? - store : - store.index(index.name); - var direction = reverse ? - unique ? - "prevunique" : - "prev" : - unique ? - "nextunique" : - "next"; - var req = values || !('openKeyCursor' in source) ? - source.openCursor(makeIDBKeyRange(range), direction) : - source.openKeyCursor(makeIDBKeyRange(range), direction); - req.onerror = eventRejectHandler(reject); - req.onsuccess = wrap(function (ev) { - var cursor = req.result; - if (!cursor) { - resolve(null); - return; - } - cursor.___id = ++_id_counter; - cursor.done = false; - var _cursorContinue = cursor.continue.bind(cursor); - var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; - if (_cursorContinuePrimaryKey) - _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); - var _cursorAdvance = cursor.advance.bind(cursor); - var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; - var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; - cursor.trans = trans; - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; - cursor.fail = wrap(reject); - cursor.next = function () { - var _this = this; - var gotOne = 1; - return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); - }; - cursor.start = function (callback) { - var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { - resolveIteration = wrap(resolveIteration); - req.onerror = eventRejectHandler(rejectIteration); - cursor.fail = rejectIteration; - cursor.stop = function (value) { - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; - resolveIteration(value); - }; - }); - var guardedCallback = function () { - if (req.result) { - try { - callback(); - } - catch (err) { - cursor.fail(err); - } - } - else { - cursor.done = true; - cursor.start = function () { throw new Error("Cursor behind last entry"); }; - cursor.stop(); - } - }; - req.onsuccess = wrap(function (ev) { - req.onsuccess = guardedCallback; - guardedCallback(); - }); - cursor.continue = _cursorContinue; - cursor.continuePrimaryKey = _cursorContinuePrimaryKey; - cursor.advance = _cursorAdvance; - guardedCallback(); - return iterationPromise; - }; - resolve(cursor); - }, reject); - }); - } - function query(hasGetAll) { - return function (request) { - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var trans = request.trans, values = request.values, limit = request.limit, query = request.query; - var nonInfinitLimit = limit === Infinity ? undefined : limit; - var index = query.index, range = query.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - if (limit === 0) - return resolve({ result: [] }); - if (hasGetAll) { - var req = values ? - source.getAll(idbKeyRange, nonInfinitLimit) : - source.getAllKeys(idbKeyRange, nonInfinitLimit); - req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; - req.onerror = eventRejectHandler(reject); - } - else { - var count_1 = 0; - var req_1 = values || !('openKeyCursor' in source) ? - source.openCursor(idbKeyRange) : - source.openKeyCursor(idbKeyRange); - var result_1 = []; - req_1.onsuccess = function (event) { - var cursor = req_1.result; - if (!cursor) - return resolve({ result: result_1 }); - result_1.push(values ? cursor.value : cursor.primaryKey); - if (++count_1 === limit) - return resolve({ result: result_1 }); - cursor.continue(); - }; - req_1.onerror = eventRejectHandler(reject); - } - }); - }; - } - return { - name: tableName, - schema: tableSchema, - mutate: mutate, - getMany: function (_a) { - var trans = _a.trans, keys = _a.keys; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var length = keys.length; - var result = new Array(length); - var keyCount = 0; - var callbackCount = 0; - var req; - var successHandler = function (event) { - var req = event.target; - if ((result[req._pos] = req.result) != null) - ; - if (++callbackCount === keyCount) - resolve(result); - }; - var errorHandler = eventRejectHandler(reject); - for (var i = 0; i < length; ++i) { - var key = keys[i]; - if (key != null) { - req = store.get(keys[i]); - req._pos = i; - req.onsuccess = successHandler; - req.onerror = errorHandler; - ++keyCount; - } - } - if (keyCount === 0) - resolve(result); - }); - }, - get: function (_a) { - var trans = _a.trans, key = _a.key; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var req = store.get(key); - req.onsuccess = function (event) { return resolve(event.target.result); }; - req.onerror = eventRejectHandler(reject); - }); - }, - query: query(hasGetAll), - openCursor: openCursor, - count: function (_a) { - var query = _a.query, trans = _a.trans; - var index = query.index, range = query.range; - return new Promise(function (resolve, reject) { - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); - req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); - req.onerror = eventRejectHandler(reject); - }); - } - }; - } - var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; - var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); - var tableMap = {}; - tables.forEach(function (table) { return tableMap[table.name] = table; }); - return { - stack: "dbcore", - transaction: db.transaction.bind(db), - table: function (name) { - var result = tableMap[name]; - if (!result) - throw new Error("Table '".concat(name, "' not found")); - return tableMap[name]; - }, - MIN_KEY: -Infinity, - MAX_KEY: getMaxKey(IdbKeyRange), - schema: schema - }; - } - - function createMiddlewareStack(stackImpl, middlewares) { - return middlewares.reduce(function (down, _a) { - var create = _a.create; - return (__assign(__assign({}, down), create(down))); - }, stackImpl); - } - function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { - var IDBKeyRange = _a.IDBKeyRange; _a.indexedDB; - var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); - return { - dbcore: dbcore - }; - } - function generateMiddlewareStacks(db, tmpTrans) { - var idbdb = tmpTrans.db; - var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); - db.core = stacks.dbcore; - db.tables.forEach(function (table) { - var tableName = table.name; - if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { - table.core = db.core.table(tableName); - if (db[tableName] instanceof db.Table) { - db[tableName].core = table.core; - } - } - }); - } - - function setApiOnPlace(db, objs, tableNames, dbschema) { - tableNames.forEach(function (tableName) { - var schema = dbschema[tableName]; - objs.forEach(function (obj) { - var propDesc = getPropertyDescriptor(obj, tableName); - if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { - if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { - setProp(obj, tableName, { - get: function () { return this.table(tableName); }, - set: function (value) { - defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); - } - }); - } - else { - obj[tableName] = new db.Table(tableName, schema); - } - } - }); - }); - } - function removeTablesApi(db, objs) { - objs.forEach(function (obj) { - for (var key in obj) { - if (obj[key] instanceof db.Table) - delete obj[key]; - } - }); - } - function lowerVersionFirst(a, b) { - return a._cfg.version - b._cfg.version; - } - function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { - var globalSchema = db._dbSchema; - if (idbUpgradeTrans.objectStoreNames.contains('$meta') && !globalSchema.$meta) { - globalSchema.$meta = createTableSchema("$meta", parseIndexSyntax("")[0], []); - db._storeNames.push('$meta'); - } - var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); - trans.create(idbUpgradeTrans); - trans._completion.catch(reject); - var rejectTransaction = trans._reject.bind(trans); - var transless = PSD.transless || PSD; - newScope(function () { - PSD.trans = trans; - PSD.transless = transless; - if (oldVersion === 0) { - keys(globalSchema).forEach(function (tableName) { - createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); - }); - generateMiddlewareStacks(db, idbUpgradeTrans); - DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); - } - else { - generateMiddlewareStacks(db, idbUpgradeTrans); - return getExistingVersion(db, trans, oldVersion) - .then(function (oldVersion) { return updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans); }) - .catch(rejectTransaction); - } - }); - } - function patchCurrentVersion(db, idbUpgradeTrans) { - createMissingTables(db._dbSchema, idbUpgradeTrans); - if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) { - idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version'); - } - var globalSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); - adjustToExistingIndexNames(db, db._dbSchema, idbUpgradeTrans); - var diff = getSchemaDiff(globalSchema, db._dbSchema); - var _loop_1 = function (tableChange) { - if (tableChange.change.length || tableChange.recreate) { - console.warn("Unable to patch indexes of table ".concat(tableChange.name, " because it has changes on the type of index or primary key.")); - return { value: void 0 }; - } - var store = idbUpgradeTrans.objectStore(tableChange.name); - tableChange.add.forEach(function (idx) { - if (debug) - console.debug("Dexie upgrade patch: Creating missing index ".concat(tableChange.name, ".").concat(idx.src)); - addIndex(store, idx); - }); - }; - for (var _i = 0, _a = diff.change; _i < _a.length; _i++) { - var tableChange = _a[_i]; - var state_1 = _loop_1(tableChange); - if (typeof state_1 === "object") - return state_1.value; - } - } - function getExistingVersion(db, trans, oldVersion) { - if (trans.storeNames.includes('$meta')) { - return trans.table('$meta').get('version').then(function (metaVersion) { - return metaVersion != null ? metaVersion : oldVersion; - }); - } - else { - return DexiePromise.resolve(oldVersion); - } - } - function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { - var queue = []; - var versions = db._versions; - var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); - var versToRun = versions.filter(function (v) { return v._cfg.version >= oldVersion; }); - if (versToRun.length === 0) { - return DexiePromise.resolve(); - } - versToRun.forEach(function (version) { - queue.push(function () { - var oldSchema = globalSchema; - var newSchema = version._cfg.dbschema; - adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans); - adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); - globalSchema = db._dbSchema = newSchema; - var diff = getSchemaDiff(oldSchema, newSchema); - diff.add.forEach(function (tuple) { - createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); - }); - diff.change.forEach(function (change) { - if (change.recreate) { - throw new exceptions.Upgrade("Not yet support for changing primary key"); - } - else { - var store_1 = idbUpgradeTrans.objectStore(change.name); - change.add.forEach(function (idx) { return addIndex(store_1, idx); }); - change.change.forEach(function (idx) { - store_1.deleteIndex(idx.name); - addIndex(store_1, idx); - }); - change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); - } - }); - var contentUpgrade = version._cfg.contentUpgrade; - if (contentUpgrade && version._cfg.version > oldVersion) { - generateMiddlewareStacks(db, idbUpgradeTrans); - trans._memoizedTables = {}; - var upgradeSchema_1 = shallowClone(newSchema); - diff.del.forEach(function (table) { - upgradeSchema_1[table] = oldSchema[table]; - }); - removeTablesApi(db, [db.Transaction.prototype]); - setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); - trans.schema = upgradeSchema_1; - var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); - if (contentUpgradeIsAsync_1) { - incrementExpectedAwaits(); - } - var returnValue_1; - var promiseFollowed = DexiePromise.follow(function () { - returnValue_1 = contentUpgrade(trans); - if (returnValue_1) { - if (contentUpgradeIsAsync_1) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue_1.then(decrementor, decrementor); - } - } - }); - return (returnValue_1 && typeof returnValue_1.then === 'function' ? - DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); - } - }); - queue.push(function (idbtrans) { - var newSchema = version._cfg.dbschema; - deleteRemovedTables(newSchema, idbtrans); - removeTablesApi(db, [db.Transaction.prototype]); - setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); - trans.schema = db._dbSchema; - }); - queue.push(function (idbtrans) { - if (db.idbdb.objectStoreNames.contains('$meta')) { - if (Math.ceil(db.idbdb.version / 10) === version._cfg.version) { - db.idbdb.deleteObjectStore('$meta'); - delete db._dbSchema.$meta; - db._storeNames = db._storeNames.filter(function (name) { return name !== '$meta'; }); - } - else { - idbtrans.objectStore('$meta').put(version._cfg.version, 'version'); - } - } - }); - }); - function runQueue() { - return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : - DexiePromise.resolve(); - } - return runQueue().then(function () { - createMissingTables(globalSchema, idbUpgradeTrans); - }); - } - function getSchemaDiff(oldSchema, newSchema) { - var diff = { - del: [], - add: [], - change: [] - }; - var table; - for (table in oldSchema) { - if (!newSchema[table]) - diff.del.push(table); - } - for (table in newSchema) { - var oldDef = oldSchema[table], newDef = newSchema[table]; - if (!oldDef) { - diff.add.push([table, newDef]); - } - else { - var change = { - name: table, - def: newDef, - recreate: false, - del: [], - add: [], - change: [] - }; - if (( - '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || - (oldDef.primKey.auto !== newDef.primKey.auto)) { - change.recreate = true; - diff.change.push(change); - } - else { - var oldIndexes = oldDef.idxByName; - var newIndexes = newDef.idxByName; - var idxName = void 0; - for (idxName in oldIndexes) { - if (!newIndexes[idxName]) - change.del.push(idxName); - } - for (idxName in newIndexes) { - var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; - if (!oldIdx) - change.add.push(newIdx); - else if (oldIdx.src !== newIdx.src) - change.change.push(newIdx); - } - if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { - diff.change.push(change); - } - } - } - } - return diff; - } - function createTable(idbtrans, tableName, primKey, indexes) { - var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? - { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : - { autoIncrement: primKey.auto }); - indexes.forEach(function (idx) { return addIndex(store, idx); }); - return store; - } - function createMissingTables(newSchema, idbtrans) { - keys(newSchema).forEach(function (tableName) { - if (!idbtrans.db.objectStoreNames.contains(tableName)) { - if (debug) - console.debug('Dexie: Creating missing table', tableName); - createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); - } - }); - } - function deleteRemovedTables(newSchema, idbtrans) { - [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { - return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); - }); - } - function addIndex(store, idx) { - store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); - } - function buildGlobalSchema(db, idbdb, tmpTrans) { - var globalSchema = {}; - var dbStoreNames = slice(idbdb.objectStoreNames, 0); - dbStoreNames.forEach(function (storeName) { - var store = tmpTrans.objectStore(storeName); - var keyPath = store.keyPath; - var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); - var indexes = []; - for (var j = 0; j < store.indexNames.length; ++j) { - var idbindex = store.index(store.indexNames[j]); - keyPath = idbindex.keyPath; - var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); - indexes.push(index); - } - globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); - }); - return globalSchema; - } - function readGlobalSchema(db, idbdb, tmpTrans) { - db.verno = idbdb.version / 10; - var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); - db._storeNames = slice(idbdb.objectStoreNames, 0); - setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); - } - function verifyInstalledSchema(db, tmpTrans) { - var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); - var diff = getSchemaDiff(installedSchema, db._dbSchema); - return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); - } - function adjustToExistingIndexNames(db, schema, idbtrans) { - var storeNames = idbtrans.db.objectStoreNames; - for (var i = 0; i < storeNames.length; ++i) { - var storeName = storeNames[i]; - var store = idbtrans.objectStore(storeName); - db._hasGetAll = 'getAll' in store; - for (var j = 0; j < store.indexNames.length; ++j) { - var indexName = store.indexNames[j]; - var keyPath = store.index(indexName).keyPath; - var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; - if (schema[storeName]) { - var indexSpec = schema[storeName].idxByName[dexieName]; - if (indexSpec) { - indexSpec.name = indexName; - delete schema[storeName].idxByName[dexieName]; - schema[storeName].idxByName[indexName] = indexSpec; - } - } - } - } - if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && - !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && - _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && - [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { - db._hasGetAll = false; - } - } - function parseIndexSyntax(primKeyAndIndexes) { - return primKeyAndIndexes.split(',').map(function (index, indexNum) { - index = index.trim(); - var name = index.replace(/([&*]|\+\+)/g, ""); - var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; - return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); - }); - } - - var Version = (function () { - function Version() { - } - Version.prototype._parseStoresSpec = function (stores, outSchema) { - keys(stores).forEach(function (tableName) { - if (stores[tableName] !== null) { - var indexes = parseIndexSyntax(stores[tableName]); - var primKey = indexes.shift(); - primKey.unique = true; - if (primKey.multi) - throw new exceptions.Schema("Primary key cannot be multi-valued"); - indexes.forEach(function (idx) { - if (idx.auto) - throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); - if (!idx.keyPath) - throw new exceptions.Schema("Index must have a name and cannot be an empty string"); - }); - outSchema[tableName] = createTableSchema(tableName, primKey, indexes); - } - }); - }; - Version.prototype.stores = function (stores) { - var db = this.db; - this._cfg.storesSource = this._cfg.storesSource ? - extend(this._cfg.storesSource, stores) : - stores; - var versions = db._versions; - var storesSpec = {}; - var dbschema = {}; - versions.forEach(function (version) { - extend(storesSpec, version._cfg.storesSource); - dbschema = (version._cfg.dbschema = {}); - version._parseStoresSpec(storesSpec, dbschema); - }); - db._dbSchema = dbschema; - removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); - setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); - db._storeNames = keys(dbschema); - return this; - }; - Version.prototype.upgrade = function (upgradeFunction) { - this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); - return this; - }; - return Version; - }()); - - function createVersionConstructor(db) { - return makeClassConstructor(Version.prototype, function Version(versionNumber) { - this.db = db; - this._cfg = { - version: versionNumber, - storesSource: null, - dbschema: {}, - tables: {}, - contentUpgrade: null - }; - }); - } - - function getDbNamesTable(indexedDB, IDBKeyRange) { - var dbNamesDB = indexedDB["_dbNamesDB"]; - if (!dbNamesDB) { - dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { - addons: [], - indexedDB: indexedDB, - IDBKeyRange: IDBKeyRange, - }); - dbNamesDB.version(1).stores({ dbnames: "name" }); - } - return dbNamesDB.table("dbnames"); - } - function hasDatabasesNative(indexedDB) { - return indexedDB && typeof indexedDB.databases === "function"; - } - function getDatabaseNames(_a) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - return hasDatabasesNative(indexedDB) - ? Promise.resolve(indexedDB.databases()).then(function (infos) { - return infos - .map(function (info) { return info.name; }) - .filter(function (name) { return name !== DBNAMES_DB; }); - }) - : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); - } - function _onDatabaseCreated(_a, name) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - !hasDatabasesNative(indexedDB) && - name !== DBNAMES_DB && - getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); - } - function _onDatabaseDeleted(_a, name) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - !hasDatabasesNative(indexedDB) && - name !== DBNAMES_DB && - getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); - } - - function vip(fn) { - return newScope(function () { - PSD.letThrough = true; - return fn(); - }); - } - - function idbReady() { - var isSafari = !navigator.userAgentData && - /Safari\//.test(navigator.userAgent) && - !/Chrom(e|ium)\//.test(navigator.userAgent); - if (!isSafari || !indexedDB.databases) - return Promise.resolve(); - var intervalId; - return new Promise(function (resolve) { - var tryIdb = function () { return indexedDB.databases().finally(resolve); }; - intervalId = setInterval(tryIdb, 100); - tryIdb(); - }).finally(function () { return clearInterval(intervalId); }); - } - - var _a; - function isEmptyRange(node) { - return !("from" in node); - } - var RangeSet = function (fromOrTree, to) { - if (this) { - extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); - } - else { - var rv = new RangeSet(); - if (fromOrTree && ("d" in fromOrTree)) { - extend(rv, fromOrTree); - } - return rv; - } - }; - props(RangeSet.prototype, (_a = { - add: function (rangeSet) { - mergeRanges(this, rangeSet); - return this; - }, - addKey: function (key) { - addRange(this, key, key); - return this; - }, - addKeys: function (keys) { - var _this = this; - keys.forEach(function (key) { return addRange(_this, key, key); }); - return this; - } - }, - _a[iteratorSymbol] = function () { - return getRangeSetIterator(this); - }, - _a)); - function addRange(target, from, to) { - var diff = cmp(from, to); - if (isNaN(diff)) - return; - if (diff > 0) - throw RangeError(); - if (isEmptyRange(target)) - return extend(target, { from: from, to: to, d: 1 }); - var left = target.l; - var right = target.r; - if (cmp(to, target.from) < 0) { - left - ? addRange(left, from, to) - : (target.l = { from: from, to: to, d: 1, l: null, r: null }); - return rebalance(target); - } - if (cmp(from, target.to) > 0) { - right - ? addRange(right, from, to) - : (target.r = { from: from, to: to, d: 1, l: null, r: null }); - return rebalance(target); - } - if (cmp(from, target.from) < 0) { - target.from = from; - target.l = null; - target.d = right ? right.d + 1 : 1; - } - if (cmp(to, target.to) > 0) { - target.to = to; - target.r = null; - target.d = target.l ? target.l.d + 1 : 1; - } - var rightWasCutOff = !target.r; - if (left && !target.l) { - mergeRanges(target, left); - } - if (right && rightWasCutOff) { - mergeRanges(target, right); - } - } - function mergeRanges(target, newSet) { - function _addRangeSet(target, _a) { - var from = _a.from, to = _a.to, l = _a.l, r = _a.r; - addRange(target, from, to); - if (l) - _addRangeSet(target, l); - if (r) - _addRangeSet(target, r); - } - if (!isEmptyRange(newSet)) - _addRangeSet(target, newSet); - } - function rangesOverlap(rangeSet1, rangeSet2) { - var i1 = getRangeSetIterator(rangeSet2); - var nextResult1 = i1.next(); - if (nextResult1.done) - return false; - var a = nextResult1.value; - var i2 = getRangeSetIterator(rangeSet1); - var nextResult2 = i2.next(a.from); - var b = nextResult2.value; - while (!nextResult1.done && !nextResult2.done) { - if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) - return true; - cmp(a.from, b.from) < 0 - ? (a = (nextResult1 = i1.next(b.from)).value) - : (b = (nextResult2 = i2.next(a.from)).value); - } - return false; - } - function getRangeSetIterator(node) { - var state = isEmptyRange(node) ? null : { s: 0, n: node }; - return { - next: function (key) { - var keyProvided = arguments.length > 0; - while (state) { - switch (state.s) { - case 0: - state.s = 1; - if (keyProvided) { - while (state.n.l && cmp(key, state.n.from) < 0) - state = { up: state, n: state.n.l, s: 1 }; - } - else { - while (state.n.l) - state = { up: state, n: state.n.l, s: 1 }; - } - case 1: - state.s = 2; - if (!keyProvided || cmp(key, state.n.to) <= 0) - return { value: state.n, done: false }; - case 2: - if (state.n.r) { - state.s = 3; - state = { up: state, n: state.n.r, s: 0 }; - continue; - } - case 3: - state = state.up; - } - } - return { done: true }; - }, - }; - } - function rebalance(target) { - var _a, _b; - var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); - var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; - if (r) { - var l = r === "r" ? "l" : "r"; - var rootClone = __assign({}, target); - var oldRootRight = target[r]; - target.from = oldRootRight.from; - target.to = oldRootRight.to; - target[r] = oldRootRight[r]; - rootClone[r] = oldRootRight[l]; - target[l] = rootClone; - rootClone.d = computeDepth(rootClone); - } - target.d = computeDepth(target); - } - function computeDepth(_a) { - var r = _a.r, l = _a.l; - return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; - } - - function extendObservabilitySet(target, newSet) { - keys(newSet).forEach(function (part) { - if (target[part]) - mergeRanges(target[part], newSet[part]); - else - target[part] = cloneSimpleObjectTree(newSet[part]); - }); - return target; - } - - function obsSetsOverlap(os1, os2) { - return os1.all || os2.all || Object.keys(os1).some(function (key) { return os2[key] && rangesOverlap(os2[key], os1[key]); }); - } - - var cache = {}; - - var unsignaledParts = {}; - var isTaskEnqueued = false; - function signalSubscribersLazily(part, optimistic) { - extendObservabilitySet(unsignaledParts, part); - if (!isTaskEnqueued) { - isTaskEnqueued = true; - setTimeout(function () { - isTaskEnqueued = false; - var parts = unsignaledParts; - unsignaledParts = {}; - signalSubscribersNow(parts, false); - }, 0); - } - } - function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { - if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; } - var queriesToSignal = new Set(); - if (updatedParts.all) { - for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) { - var tblCache = _a[_i]; - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - else { - for (var key in updatedParts) { - var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); - if (parts) { - var dbName = parts[1], tableName = parts[2]; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (tblCache) - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - } - queriesToSignal.forEach(function (requery) { return requery(); }); - } - function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { - var updatedEntryLists = []; - for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) { - var _b = _a[_i], indexName = _b[0], entries = _b[1]; - var filteredEntries = []; - for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { - var entry = entries_1[_c]; - if (obsSetsOverlap(updatedParts, entry.obsSet)) { - entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); }); - } - else if (deleteAffectedCacheEntries) { - filteredEntries.push(entry); - } - } - if (deleteAffectedCacheEntries) - updatedEntryLists.push([indexName, filteredEntries]); - } - if (deleteAffectedCacheEntries) { - for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { - var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; - tblCache.queries.query[indexName] = filteredEntries; - } - } - } - - function dexieOpen(db) { - var state = db._state; - var indexedDB = db._deps.indexedDB; - if (state.isBeingOpened || db.idbdb) - return state.dbReadyPromise.then(function () { return state.dbOpenError ? - rejection(state.dbOpenError) : - db; }); - state.isBeingOpened = true; - state.dbOpenError = null; - state.openComplete = false; - var openCanceller = state.openCanceller; - var nativeVerToOpen = Math.round(db.verno * 10); - var schemaPatchMode = false; - function throwIfCancelled() { - if (state.openCanceller !== openCanceller) - throw new exceptions.DatabaseClosed('db.open() was cancelled'); - } - var resolveDbReady = state.dbReadyResolve, - upgradeTransaction = null, wasCreated = false; - var tryOpenDB = function () { return new DexiePromise(function (resolve, reject) { - throwIfCancelled(); - if (!indexedDB) - throw new exceptions.MissingAPI(); - var dbName = db.name; - var req = state.autoSchema || !nativeVerToOpen ? - indexedDB.open(dbName) : - indexedDB.open(dbName, nativeVerToOpen); - if (!req) - throw new exceptions.MissingAPI(); - req.onerror = eventRejectHandler(reject); - req.onblocked = wrap(db._fireOnBlocked); - req.onupgradeneeded = wrap(function (e) { - upgradeTransaction = req.transaction; - if (state.autoSchema && !db._options.allowEmptyDB) { - req.onerror = preventDefault; - upgradeTransaction.abort(); - req.result.close(); - var delreq = indexedDB.deleteDatabase(dbName); - delreq.onsuccess = delreq.onerror = wrap(function () { - reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); - }); - } - else { - upgradeTransaction.onerror = eventRejectHandler(reject); - var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; - wasCreated = oldVer < 1; - db.idbdb = req.result; - if (schemaPatchMode) { - patchCurrentVersion(db, upgradeTransaction); - } - runUpgraders(db, oldVer / 10, upgradeTransaction, reject); - } - }, reject); - req.onsuccess = wrap(function () { - upgradeTransaction = null; - var idbdb = db.idbdb = req.result; - var objectStoreNames = slice(idbdb.objectStoreNames); - if (objectStoreNames.length > 0) - try { - var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); - if (state.autoSchema) - readGlobalSchema(db, idbdb, tmpTrans); - else { - adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); - if (!verifyInstalledSchema(db, tmpTrans) && !schemaPatchMode) { - 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."); - idbdb.close(); - nativeVerToOpen = idbdb.version + 1; - schemaPatchMode = true; - return resolve(tryOpenDB()); - } - } - generateMiddlewareStacks(db, tmpTrans); - } - catch (e) { - } - connections.push(db); - idbdb.onversionchange = wrap(function (ev) { - state.vcFired = true; - db.on("versionchange").fire(ev); - }); - idbdb.onclose = wrap(function (ev) { - db.on("close").fire(ev); - }); - if (wasCreated) - _onDatabaseCreated(db._deps, dbName); - resolve(); - }, reject); - }).catch(function (err) { - switch (err === null || err === void 0 ? void 0 : err.name) { - case "UnknownError": - if (state.PR1398_maxLoop > 0) { - state.PR1398_maxLoop--; - console.warn('Dexie: Workaround for Chrome UnknownError on open()'); - return tryOpenDB(); - } - break; - case "VersionError": - if (nativeVerToOpen > 0) { - nativeVerToOpen = 0; - return tryOpenDB(); - } - break; - } - return DexiePromise.reject(err); - }); }; - return DexiePromise.race([ - openCanceller, - (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) - ]).then(function () { - throwIfCancelled(); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { - if (state.onReadyBeingFired.length > 0) { - var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); - } - }); - }).finally(function () { - if (state.openCanceller === openCanceller) { - state.onReadyBeingFired = null; - state.isBeingOpened = false; - } - }).catch(function (err) { - state.dbOpenError = err; - try { - upgradeTransaction && upgradeTransaction.abort(); - } - catch (_a) { } - if (openCanceller === state.openCanceller) { - db._close(); - } - return rejection(err); - }).finally(function () { - state.openComplete = true; - resolveDbReady(); - }).then(function () { - if (wasCreated) { - var everything_1 = {}; - db.tables.forEach(function (table) { - table.schema.indexes.forEach(function (idx) { - if (idx.name) - everything_1["idb://".concat(db.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet(-Infinity, [[[]]]); - }); - everything_1["idb://".concat(db.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db.name, "/").concat(table.name, "/:dels")] = new RangeSet(-Infinity, [[[]]]); - }); - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); - signalSubscribersNow(everything_1, true); - } - return db; - }); - } - - function awaitIterator(iterator) { - var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); - function step(getNext) { - return function (val) { - var next = getNext(val), value = next.value; - return next.done ? value : - (!value || typeof value.then !== 'function' ? - isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : - value.then(onSuccess, onError)); - }; - } - return step(callNext)(); - } - - function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { - var i = arguments.length; - if (i < 2) - throw new exceptions.InvalidArgument("Too few arguments"); - var args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - scopeFunc = args.pop(); - var tables = flatten(args); - return [mode, tables, scopeFunc]; - } - function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { - return DexiePromise.resolve().then(function () { - var transless = PSD.transless || PSD; - var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); - trans.explicit = true; - var zoneProps = { - trans: trans, - transless: transless - }; - if (parentTransaction) { - trans.idbtrans = parentTransaction.idbtrans; - } - else { - try { - trans.create(); - trans.idbtrans._explicit = true; - db._state.PR1398_maxLoop = 3; - } - catch (ex) { - if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { - console.warn('Dexie: Need to reopen db'); - db.close({ disableAutoOpen: false }); - return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); - } - return rejection(ex); - } - } - var scopeFuncIsAsync = isAsyncFunction(scopeFunc); - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var returnValue; - var promiseFollowed = DexiePromise.follow(function () { - returnValue = scopeFunc.call(trans, trans); - if (returnValue) { - if (scopeFuncIsAsync) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue.then(decrementor, decrementor); - } - else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { - returnValue = awaitIterator(returnValue); - } - } - }, zoneProps); - return (returnValue && typeof returnValue.then === 'function' ? - DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? - x - : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) - : promiseFollowed.then(function () { return returnValue; })).then(function (x) { - if (parentTransaction) - trans._resolve(); - return trans._completion.then(function () { return x; }); - }).catch(function (e) { - trans._reject(e); - return rejection(e); - }); - }); - } - - function pad(a, value, count) { - var result = isArray(a) ? a.slice() : [a]; - for (var i = 0; i < count; ++i) - result.push(value); - return result; - } - function createVirtualIndexMiddleware(down) { - return __assign(__assign({}, down), { table: function (tableName) { - var table = down.table(tableName); - var schema = table.schema; - var indexLookup = {}; - var allVirtualIndexes = []; - function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { - var keyPathAlias = getKeyPathAlias(keyPath); - var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); - var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; - var isVirtual = keyTail > 0; - var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual - ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") - : lowLevelIndex.name, lowLevelIndex: lowLevelIndex, isVirtual: isVirtual, keyTail: keyTail, keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); - indexList.push(virtualIndex); - if (!virtualIndex.isPrimaryKey) { - allVirtualIndexes.push(virtualIndex); - } - if (keyLength > 1) { - var virtualKeyPath = keyLength === 2 ? - keyPath[0] : - keyPath.slice(0, keyLength - 1); - addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); - } - indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); - return virtualIndex; - } - var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); - indexLookup[":id"] = [primaryKey]; - for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { - var index = _a[_i]; - addVirtualIndexes(index.keyPath, 0, index); - } - function findBestIndex(keyPath) { - var result = indexLookup[getKeyPathAlias(keyPath)]; - return result && result[0]; - } - function translateRange(range, keyTail) { - return { - type: range.type === 1 ? - 2 : - range.type, - lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), - lowerOpen: true, - upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), - upperOpen: true - }; - } - function translateRequest(req) { - var index = req.query.index; - return index.isVirtual ? __assign(__assign({}, req), { query: { - index: index.lowLevelIndex, - range: translateRange(req.query.range, index.keyTail) - } }) : req; - } - var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { - return table.count(translateRequest(req)); - }, query: function (req) { - return table.query(translateRequest(req)); - }, openCursor: function (req) { - var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; - if (!isVirtual) - return table.openCursor(req); - function createVirtualCursor(cursor) { - function _continue(key) { - key != null ? - cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : - req.unique ? - cursor.continue(cursor.key.slice(0, keyLength) - .concat(req.reverse - ? down.MIN_KEY - : down.MAX_KEY, keyTail)) : - cursor.continue(); - } - var virtualCursor = Object.create(cursor, { - continue: { value: _continue }, - continuePrimaryKey: { - value: function (key, primaryKey) { - cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); - } - }, - primaryKey: { - get: function () { - return cursor.primaryKey; - } - }, - key: { - get: function () { - var key = cursor.key; - return keyLength === 1 ? - key[0] : - key.slice(0, keyLength); - } - }, - value: { - get: function () { - return cursor.value; - } - } - }); - return virtualCursor; - } - return table.openCursor(translateRequest(req)) - .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); - } }); - return result; - } }); - } - var virtualIndexMiddleware = { - stack: "dbcore", - name: "VirtualIndexMiddleware", - level: 1, - create: createVirtualIndexMiddleware - }; - - function getObjectDiff(a, b, rv, prfx) { - rv = rv || {}; - prfx = prfx || ''; - keys(a).forEach(function (prop) { - if (!hasOwn(b, prop)) { - rv[prfx + prop] = undefined; - } - else { - var ap = a[prop], bp = b[prop]; - if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { - var apTypeName = toStringTag(ap); - var bpTypeName = toStringTag(bp); - if (apTypeName !== bpTypeName) { - rv[prfx + prop] = b[prop]; - } - else if (apTypeName === 'Object') { - getObjectDiff(ap, bp, rv, prfx + prop + '.'); - } - else if (ap !== bp) { - rv[prfx + prop] = b[prop]; - } - } - else if (ap !== bp) - rv[prfx + prop] = b[prop]; - } - }); - keys(b).forEach(function (prop) { - if (!hasOwn(a, prop)) { - rv[prfx + prop] = b[prop]; - } - }); - return rv; - } - - function getEffectiveKeys(primaryKey, req) { - if (req.type === 'delete') - return req.keys; - return req.keys || req.values.map(primaryKey.extractKey); - } - - var hooksMiddleware = { - stack: "dbcore", - name: "HooksMiddleware", - level: 2, - create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { - var downTable = downCore.table(tableName); - var primaryKey = downTable.schema.primaryKey; - var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { - var dxTrans = PSD.trans; - var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; - switch (req.type) { - case 'add': - if (creating.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'put': - if (creating.fire === nop && updating.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'delete': - if (deleting.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'deleteRange': - if (deleting.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); - } - return downTable.mutate(req); - function addPutOrDelete(req) { - var dxTrans = PSD.trans; - var keys = req.keys || getEffectiveKeys(primaryKey, req); - if (!keys) - throw new Error("Keys missing"); - req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); - if (req.type !== 'delete') - req.values = __spreadArray([], req.values, true); - if (req.keys) - req.keys = __spreadArray([], req.keys, true); - return getExistingValues(downTable, req, keys).then(function (existingValues) { - var contexts = keys.map(function (key, i) { - var existingValue = existingValues[i]; - var ctx = { onerror: null, onsuccess: null }; - if (req.type === 'delete') { - deleting.fire.call(ctx, key, existingValue, dxTrans); - } - else if (req.type === 'add' || existingValue === undefined) { - var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); - if (key == null && generatedPrimaryKey != null) { - key = generatedPrimaryKey; - req.keys[i] = key; - if (!primaryKey.outbound) { - setByKeyPath(req.values[i], primaryKey.keyPath, key); - } - } - } - else { - var objectDiff = getObjectDiff(existingValue, req.values[i]); - var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); - if (additionalChanges_1) { - var requestedValue_1 = req.values[i]; - Object.keys(additionalChanges_1).forEach(function (keyPath) { - if (hasOwn(requestedValue_1, keyPath)) { - requestedValue_1[keyPath] = additionalChanges_1[keyPath]; - } - else { - setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); - } - }); - } - } - return ctx; - }); - return downTable.mutate(req).then(function (_a) { - var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; - for (var i = 0; i < keys.length; ++i) { - var primKey = results ? results[i] : keys[i]; - var ctx = contexts[i]; - if (primKey == null) { - ctx.onerror && ctx.onerror(failures[i]); - } - else { - ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? - req.values[i] : - primKey - ); - } - } - return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; - }).catch(function (error) { - contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); - return Promise.reject(error); - }); - }); - } - function deleteRange(req) { - return deleteNextChunk(req.trans, req.range, 10000); - } - function deleteNextChunk(trans, range, limit) { - return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) - .then(function (_a) { - var result = _a.result; - return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { - if (res.numFailures > 0) - return Promise.reject(res.failures[0]); - if (result.length < limit) { - return { failures: [], numFailures: 0, lastResult: undefined }; - } - else { - return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); - } - }); - }); - } - } }); - return tableMiddleware; - } })); } - }; - function getExistingValues(table, req, effectiveKeys) { - return req.type === "add" - ? Promise.resolve([]) - : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); - } - - function getFromTransactionCache(keys, cache, clone) { - try { - if (!cache) - return null; - if (cache.keys.length < keys.length) - return null; - var result = []; - for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { - if (cmp(cache.keys[i], keys[j]) !== 0) - continue; - result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); - ++j; - } - return result.length === keys.length ? result : null; - } - catch (_a) { - return null; - } - } - var cacheExistingValuesMiddleware = { - stack: "dbcore", - level: -1, - create: function (core) { - return { - table: function (tableName) { - var table = core.table(tableName); - return __assign(__assign({}, table), { getMany: function (req) { - if (!req.cache) { - return table.getMany(req); - } - var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); - if (cachedResult) { - return DexiePromise.resolve(cachedResult); - } - return table.getMany(req).then(function (res) { - req.trans["_cache"] = { - keys: req.keys, - values: req.cache === "clone" ? deepClone(res) : res, - }; - return res; - }); - }, mutate: function (req) { - if (req.type !== "add") - req.trans["_cache"] = null; - return table.mutate(req); - } }); - }, - }; - }, - }; - - function isCachableContext(ctx, table) { - return (ctx.trans.mode === 'readonly' && - !!ctx.subscr && - !ctx.trans.explicit && - ctx.trans.db._options.cache !== 'disabled' && - !table.schema.primaryKey.outbound); - } - - function isCachableRequest(type, req) { - switch (type) { - case 'query': - return req.values && !req.unique; - case 'get': - return false; - case 'getMany': - return false; - case 'count': - return false; - case 'openCursor': - return false; - } - } - - var observabilityMiddleware = { - stack: "dbcore", - level: 0, - name: "Observability", - create: function (core) { - var dbName = core.schema.name; - var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); - return __assign(__assign({}, core), { transaction: function (stores, mode, options) { - if (PSD.subscr && mode !== 'readonly') { - throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); - } - return core.transaction(stores, mode, options); - }, table: function (tableName) { - var table = core.table(tableName); - var schema = table.schema; - var primaryKey = schema.primaryKey, indexes = schema.indexes; - var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; - var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function (index) { return index.compound && index.keyPath.includes(primaryKey.keyPath); }); - var tableClone = __assign(__assign({}, table), { mutate: function (req) { - var trans = req.trans; - var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); - var getRangeSet = function (indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return (mutatedParts[part] || - (mutatedParts[part] = new RangeSet())); - }; - var pkRangeSet = getRangeSet(""); - var delsRangeSet = getRangeSet(":dels"); - var type = req.type; - var _a = req.type === "deleteRange" - ? [req.range] - : req.type === "delete" - ? [req.keys] - : req.values.length < 50 - ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values] - : [], keys = _a[0], newObjs = _a[1]; - var oldCache = req.trans["_cache"]; - if (isArray(keys)) { - pkRangeSet.addKeys(keys); - var oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null; - if (!oldObjs) { - delsRangeSet.addKeys(keys); - } - if (oldObjs || newObjs) { - trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); - } - } - else if (keys) { - var range = { from: keys.lower, to: keys.upper }; - delsRangeSet.add(range); - pkRangeSet.add(range); - } - else { - pkRangeSet.add(FULL_RANGE); - delsRangeSet.add(FULL_RANGE); - schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); - } - return table.mutate(req).then(function (res) { - if (keys && (req.type === 'add' || req.type === 'put')) { - pkRangeSet.addKeys(res.results); - if (indexesWithAutoIncPK) { - indexesWithAutoIncPK.forEach(function (idx) { - var idxVals = req.values.map(function (v) { return idx.extractKey(v); }); - var pkPos = idx.keyPath.findIndex(function (prop) { return prop === primaryKey.keyPath; }); - res.results.forEach(function (pk) { return idxVals[pkPos] = pk; }); - getRangeSet(idx.name).addKeys(idxVals); - }); - } - } - trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); - return res; - }); - } }); - var getRange = function (_a) { - var _b, _c; - var _d = _a.query, index = _d.index, range = _d.range; - return [ - index, - new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), - ]; - }; - var readSubscribers = { - get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, - getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, - count: getRange, - query: getRange, - openCursor: getRange, - }; - keys(readSubscribers).forEach(function (method) { - tableClone[method] = function (req) { - var subscr = PSD.subscr; - var isLiveQuery = !!subscr; - var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); - var obsSet = cachable - ? req.obsSet = {} - : subscr; - if (isLiveQuery) { - var getRangeSet = function (indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return (obsSet[part] || - (obsSet[part] = new RangeSet())); - }; - var pkRangeSet_1 = getRangeSet(""); - var delsRangeSet_1 = getRangeSet(":dels"); - var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; - if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) { - delsRangeSet_1.add(queriedRanges); - } - else { - getRangeSet(queriedIndex.name || "").add(queriedRanges); - } - if (!queriedIndex.isPrimaryKey) { - if (method === "count") { - delsRangeSet_1.add(FULL_RANGE); - } - else { - var keysPromise_1 = method === "query" && - outbound && - req.values && - table.query(__assign(__assign({}, req), { values: false })); - return table[method].apply(this, arguments).then(function (res) { - if (method === "query") { - if (outbound && req.values) { - return keysPromise_1.then(function (_a) { - var resultingKeys = _a.result; - pkRangeSet_1.addKeys(resultingKeys); - return res; - }); - } - var pKeys = req.values - ? res.result.map(extractKey) - : res.result; - if (req.values) { - pkRangeSet_1.addKeys(pKeys); - } - else { - delsRangeSet_1.addKeys(pKeys); - } - } - else if (method === "openCursor") { - var cursor_1 = res; - var wantValues_1 = req.values; - return (cursor_1 && - Object.create(cursor_1, { - key: { - get: function () { - delsRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.key; - }, - }, - primaryKey: { - get: function () { - var pkey = cursor_1.primaryKey; - delsRangeSet_1.addKey(pkey); - return pkey; - }, - }, - value: { - get: function () { - wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.value; - }, - }, - })); - } - return res; - }); - } - } - } - return table[method].apply(this, arguments); - }; - }); - return tableClone; - } }); - }, - }; - function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { - function addAffectedIndex(ix) { - var rangeSet = getRangeSet(ix.name || ""); - function extractKey(obj) { - return obj != null ? ix.extractKey(obj) : null; - } - var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) - ? key.forEach(function (key) { return rangeSet.addKey(key); }) - : rangeSet.addKey(key); }; - (oldObjs || newObjs).forEach(function (_, i) { - var oldKey = oldObjs && extractKey(oldObjs[i]); - var newKey = newObjs && extractKey(newObjs[i]); - if (cmp(oldKey, newKey) !== 0) { - if (oldKey != null) - addKeyOrKeys(oldKey); - if (newKey != null) - addKeyOrKeys(newKey); - } - }); - } - schema.indexes.forEach(addAffectedIndex); - } - - function adjustOptimisticFromFailures(tblCache, req, res) { - if (res.numFailures === 0) - return req; - if (req.type === 'deleteRange') { - return null; - } - var numBulkOps = req.keys - ? req.keys.length - : 'values' in req && req.values - ? req.values.length - : 1; - if (res.numFailures === numBulkOps) { - return null; - } - var clone = __assign({}, req); - if (isArray(clone.keys)) { - clone.keys = clone.keys.filter(function (_, i) { return !(i in res.failures); }); - } - if ('values' in clone && isArray(clone.values)) { - clone.values = clone.values.filter(function (_, i) { return !(i in res.failures); }); - } - return clone; - } - - function isAboveLower(key, range) { - return range.lower === undefined - ? true - : range.lowerOpen - ? cmp(key, range.lower) > 0 - : cmp(key, range.lower) >= 0; - } - function isBelowUpper(key, range) { - return range.upper === undefined - ? true - : range.upperOpen - ? cmp(key, range.upper) < 0 - : cmp(key, range.upper) <= 0; - } - function isWithinRange(key, range) { - return isAboveLower(key, range) && isBelowUpper(key, range); - } - - function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { - if (!ops || ops.length === 0) - return result; - var index = req.query.index; - var multiEntry = index.multiEntry; - var queryRange = req.query.range; - var primaryKey = table.schema.primaryKey; - var extractPrimKey = primaryKey.extractKey; - var extractIndex = index.extractKey; - var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; - var finalResult = ops.reduce(function (result, op) { - var modifedResult = result; - var includedValues = op.type === 'add' || op.type === 'put' - ? op.values.filter(function (v) { - var key = extractIndex(v); - return multiEntry && isArray(key) - ? key.some(function (k) { return isWithinRange(k, queryRange); }) - : isWithinRange(key, queryRange); - }).map(function (v) { - v = deepClone(v); - if (immutable) - Object.freeze(v); - return v; - }) - : []; - switch (op.type) { - case 'add': - modifedResult = result.concat(req.values - ? includedValues - : includedValues.map(function (v) { return extractPrimKey(v); })); - break; - case 'put': - var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); })); - modifedResult = result - .filter(function (item) { - var key = req.values ? extractPrimKey(item) : item; - return !rangesOverlap(new RangeSet(key), keySet_1); - }) - .concat(req.values - ? includedValues - : includedValues.map(function (v) { return extractPrimKey(v); })); - break; - case 'delete': - var keysToDelete_1 = new RangeSet().addKeys(op.keys); - modifedResult = result.filter(function (item) { - var key = req.values ? extractPrimKey(item) : item; - return !rangesOverlap(new RangeSet(key), keysToDelete_1); - }); - break; - case 'deleteRange': - var range_1 = op.range; - modifedResult = result.filter(function (item) { return !isWithinRange(extractPrimKey(item), range_1); }); - break; - } - return modifedResult; - }, result); - if (finalResult === result) - return result; - finalResult.sort(function (a, b) { - return cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) || - cmp(extractPrimKey(a), extractPrimKey(b)); - }); - if (req.limit && req.limit < Infinity) { - if (finalResult.length > req.limit) { - finalResult.length = req.limit; - } - else if (result.length === req.limit && finalResult.length < req.limit) { - cacheEntry.dirty = true; - } - } - return immutable ? Object.freeze(finalResult) : finalResult; - } - - function areRangesEqual(r1, r2) { - return (cmp(r1.lower, r2.lower) === 0 && - cmp(r1.upper, r2.upper) === 0 && - !!r1.lowerOpen === !!r2.lowerOpen && - !!r1.upperOpen === !!r2.upperOpen); - } - - function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { - if (lower1 === undefined) - return lower2 !== undefined ? -1 : 0; - if (lower2 === undefined) - return 1; - var c = cmp(lower1, lower2); - if (c === 0) { - if (lowerOpen1 && lowerOpen2) - return 0; - if (lowerOpen1) - return 1; - if (lowerOpen2) - return -1; - } - return c; - } - function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { - if (upper1 === undefined) - return upper2 !== undefined ? 1 : 0; - if (upper2 === undefined) - return -1; - var c = cmp(upper1, upper2); - if (c === 0) { - if (upperOpen1 && upperOpen2) - return 0; - if (upperOpen1) - return -1; - if (upperOpen2) - return 1; - } - return c; - } - function isSuperRange(r1, r2) { - return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && - compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0); - } - - function findCompatibleQuery(dbName, tableName, type, req) { - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return []; - var queries = tblCache.queries[type]; - if (!queries) - return [null, false, tblCache, null]; - var indexName = req.query ? req.query.index.name : null; - var entries = queries[indexName || '']; - if (!entries) - return [null, false, tblCache, null]; - switch (type) { - case 'query': - var equalEntry = entries.find(function (entry) { - return entry.req.limit === req.limit && - entry.req.values === req.values && - areRangesEqual(entry.req.query.range, req.query.range); - }); - if (equalEntry) - return [ - equalEntry, - true, - tblCache, - entries, - ]; - var superEntry = entries.find(function (entry) { - var limit = 'limit' in entry.req ? entry.req.limit : Infinity; - return (limit >= req.limit && - (req.values ? entry.req.values : true) && - isSuperRange(entry.req.query.range, req.query.range)); - }); - return [superEntry, false, tblCache, entries]; - case 'count': - var countQuery = entries.find(function (entry) { - return areRangesEqual(entry.req.query.range, req.query.range); - }); - return [countQuery, !!countQuery, tblCache, entries]; - } - } - - function subscribeToCacheEntry(cacheEntry, container, requery, signal) { - cacheEntry.subscribers.add(requery); - signal.addEventListener("abort", function () { - cacheEntry.subscribers.delete(requery); - if (cacheEntry.subscribers.size === 0) { - enqueForDeletion(cacheEntry, container); - } - }); - } - function enqueForDeletion(cacheEntry, container) { - setTimeout(function () { - if (cacheEntry.subscribers.size === 0) { - delArrayItem(container, cacheEntry); - } - }, 3000); - } - - var cacheMiddleware = { - stack: 'dbcore', - level: 0, - name: 'Cache', - create: function (core) { - var dbName = core.schema.name; - var coreMW = __assign(__assign({}, core), { transaction: function (stores, mode, options) { - var idbtrans = core.transaction(stores, mode, options); - if (mode === 'readwrite') { - var ac_1 = new AbortController(); - var signal = ac_1.signal; - var endTransaction = function (wasCommitted) { return function () { - ac_1.abort(); - if (mode === 'readwrite') { - var affectedSubscribers_1 = new Set(); - for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { - var storeName = stores_1[_i]; - var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; - if (tblCache) { - var table = core.table(storeName); - var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; }); - if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) { - for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) { - var entries = _b[_a]; - for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { - var entry = _d[_c]; - if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - } - } - } - else if (ops.length > 0) { - tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; }); - for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) { - var entries = _f[_e]; - for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) { - var entry = _h[_g]; - if (entry.res != null && - idbtrans.mutatedParts - ) { - if (wasCommitted && !entry.dirty) { - var freezeResults = Object.isFrozen(entry.res); - var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); - if (entry.dirty) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - else if (modRes !== entry.res) { - entry.res = modRes; - entry.promise = DexiePromise.resolve({ result: modRes }); - } - } - else { - if (entry.dirty) { - delArrayItem(entries, entry); - } - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - } - } - } - } - } - } - affectedSubscribers_1.forEach(function (requery) { return requery(); }); - } - }; }; - idbtrans.addEventListener('abort', endTransaction(false), { - signal: signal, - }); - idbtrans.addEventListener('error', endTransaction(false), { - signal: signal, - }); - idbtrans.addEventListener('complete', endTransaction(true), { - signal: signal, - }); - } - return idbtrans; - }, table: function (tableName) { - var downTable = core.table(tableName); - var primKey = downTable.schema.primaryKey; - var tableMW = __assign(__assign({}, downTable), { mutate: function (req) { - var trans = PSD.trans; - if (primKey.outbound || - trans.db._options.cache === 'disabled' || - trans.explicit - ) { - return downTable.mutate(req); - } - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return downTable.mutate(req); - var promise = downTable.mutate(req); - if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function (key) { return key == null; }))) { - promise.then(function (res) { - var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function (value, i) { - var _a; - var valueWithKey = ((_a = primKey.keyPath) === null || _a === void 0 ? void 0 : _a.includes('.')) - ? deepClone(value) - : __assign({}, value); - setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); - return valueWithKey; - }) }); - var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res); - tblCache.optimisticOps.push(adjustedReq); - queueMicrotask(function () { return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); }); - }); - } - else { - tblCache.optimisticOps.push(req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - promise.then(function (res) { - if (res.numFailures > 0) { - delArrayItem(tblCache.optimisticOps, req); - var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res); - if (adjustedReq) { - tblCache.optimisticOps.push(adjustedReq); - } - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - } - }); - promise.catch(function () { - delArrayItem(tblCache.optimisticOps, req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - } - return promise; - }, query: function (req) { - var _a; - if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) - return downTable.query(req); - var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable'; - var _b = PSD, requery = _b.requery, signal = _b.signal; - var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3]; - if (cacheEntry && exactMatch) { - cacheEntry.obsSet = req.obsSet; - } - else { - var promise = downTable.query(req).then(function (res) { - var result = res.result; - if (cacheEntry) - cacheEntry.res = result; - if (freezeResults) { - for (var i = 0, l = result.length; i < l; ++i) { - Object.freeze(result[i]); - } - Object.freeze(result); - } - else { - res.result = deepClone(result); - } - return res; - }).catch(function (error) { - if (container && cacheEntry) - delArrayItem(container, cacheEntry); - return Promise.reject(error); - }); - cacheEntry = { - obsSet: req.obsSet, - promise: promise, - subscribers: new Set(), - type: 'query', - req: req, - dirty: false, - }; - if (container) { - container.push(cacheEntry); - } - else { - container = [cacheEntry]; - if (!tblCache) { - tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { - queries: { - query: {}, - count: {}, - }, - objs: new Map(), - optimisticOps: [], - unsignaledParts: {} - }; - } - tblCache.queries.query[req.query.index.name || ''] = container; - } - } - subscribeToCacheEntry(cacheEntry, container, requery, signal); - return cacheEntry.promise.then(function (res) { - return { - result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults), - }; - }); - } }); - return tableMW; - } }); - return coreMW; - }, - }; - - function vipify(target, vipDb) { - return new Proxy(target, { - get: function (target, prop, receiver) { - if (prop === 'db') - return vipDb; - return Reflect.get(target, prop, receiver); - } - }); - } - - var Dexie$1 = (function () { - function Dexie(name, options) { - var _this = this; - this._middlewares = {}; - this.verno = 0; - var deps = Dexie.dependencies; - this._options = options = __assign({ - addons: Dexie.addons, autoOpen: true, - indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange, cache: 'cloned' }, options); - this._deps = { - indexedDB: options.indexedDB, - IDBKeyRange: options.IDBKeyRange - }; - var addons = options.addons; - this._dbSchema = {}; - this._versions = []; - this._storeNames = []; - this._allTables = {}; - this.idbdb = null; - this._novip = this; - var state = { - dbOpenError: null, - isBeingOpened: false, - onReadyBeingFired: null, - openComplete: false, - dbReadyResolve: nop, - dbReadyPromise: null, - cancelOpen: nop, - openCanceller: null, - autoSchema: true, - PR1398_maxLoop: 3, - autoOpen: options.autoOpen, - }; - state.dbReadyPromise = new DexiePromise(function (resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function (_, reject) { - state.cancelOpen = reject; - }); - this._state = state; - this.name = name; - this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); - this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { - return function (subscriber, bSticky) { - Dexie.vip(function () { - var state = _this._state; - if (state.openComplete) { - if (!state.dbOpenError) - DexiePromise.resolve().then(subscriber); - if (bSticky) - subscribe(subscriber); - } - else if (state.onReadyBeingFired) { - state.onReadyBeingFired.push(subscriber); - if (bSticky) - subscribe(subscriber); - } - else { - subscribe(subscriber); - var db_1 = _this; - if (!bSticky) - subscribe(function unsubscribe() { - db_1.on.ready.unsubscribe(subscriber); - db_1.on.ready.unsubscribe(unsubscribe); - }); - } - }); - }; - }); - this.Collection = createCollectionConstructor(this); - this.Table = createTableConstructor(this); - this.Transaction = createTransactionConstructor(this); - this.Version = createVersionConstructor(this); - this.WhereClause = createWhereClauseConstructor(this); - this.on("versionchange", function (ev) { - if (ev.newVersion > 0) - console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); - else - console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); - _this.close({ disableAutoOpen: false }); - }); - this.on("blocked", function (ev) { - if (!ev.newVersion || ev.newVersion < ev.oldVersion) - console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); - else - console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); - }); - this._maxKey = getMaxKey(options.IDBKeyRange); - this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); }; - this._fireOnBlocked = function (ev) { - _this.on("blocked").fire(ev); - connections - .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) - .map(function (c) { return c.on("versionchange").fire(ev); }); - }; - this.use(cacheExistingValuesMiddleware); - this.use(cacheMiddleware); - this.use(observabilityMiddleware); - this.use(virtualIndexMiddleware); - this.use(hooksMiddleware); - var vipDB = new Proxy(this, { - get: function (_, prop, receiver) { - if (prop === '_vip') - return true; - if (prop === 'table') - return function (tableName) { return vipify(_this.table(tableName), vipDB); }; - var rv = Reflect.get(_, prop, receiver); - if (rv instanceof Table) - return vipify(rv, vipDB); - if (prop === 'tables') - return rv.map(function (t) { return vipify(t, vipDB); }); - if (prop === '_createTransaction') - return function () { - var tx = rv.apply(this, arguments); - return vipify(tx, vipDB); - }; - return rv; - } - }); - this.vip = vipDB; - addons.forEach(function (addon) { return addon(_this); }); - } - Dexie.prototype.version = function (versionNumber) { - if (isNaN(versionNumber) || versionNumber < 0.1) - throw new exceptions.Type("Given version is not a positive number"); - versionNumber = Math.round(versionNumber * 10) / 10; - if (this.idbdb || this._state.isBeingOpened) - throw new exceptions.Schema("Cannot add version when database is open"); - this.verno = Math.max(this.verno, versionNumber); - var versions = this._versions; - var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; - if (versionInstance) - return versionInstance; - versionInstance = new this.Version(versionNumber); - versions.push(versionInstance); - versions.sort(lowerVersionFirst); - versionInstance.stores({}); - this._state.autoSchema = false; - return versionInstance; - }; - Dexie.prototype._whenReady = function (fn) { - var _this = this; - return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { - if (_this._state.openComplete) { - return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); - } - if (!_this._state.isBeingOpened) { - if (!_this._state.autoOpen) { - reject(new exceptions.DatabaseClosed()); - return; - } - _this.open().catch(nop); - } - _this._state.dbReadyPromise.then(resolve, reject); - }).then(fn); - }; - Dexie.prototype.use = function (_a) { - var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; - if (name) - this.unuse({ stack: stack, name: name }); - var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); - middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); - middlewares.sort(function (a, b) { return a.level - b.level; }); - return this; - }; - Dexie.prototype.unuse = function (_a) { - var stack = _a.stack, name = _a.name, create = _a.create; - if (stack && this._middlewares[stack]) { - this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { - return create ? mw.create !== create : - name ? mw.name !== name : - false; - }); - } - return this; - }; - Dexie.prototype.open = function () { - var _this = this; - return usePSD(globalPSD, - function () { return dexieOpen(_this); }); - }; - Dexie.prototype._close = function () { - var state = this._state; - var idx = connections.indexOf(this); - if (idx >= 0) - connections.splice(idx, 1); - if (this.idbdb) { - try { - this.idbdb.close(); - } - catch (e) { } - this.idbdb = null; - } - if (!state.isBeingOpened) { - state.dbReadyPromise = new DexiePromise(function (resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function (_, reject) { - state.cancelOpen = reject; - }); - } - }; - Dexie.prototype.close = function (_a) { - var _b = _a === void 0 ? { disableAutoOpen: true } : _a, disableAutoOpen = _b.disableAutoOpen; - var state = this._state; - if (disableAutoOpen) { - if (state.isBeingOpened) { - state.cancelOpen(new exceptions.DatabaseClosed()); - } - this._close(); - state.autoOpen = false; - state.dbOpenError = new exceptions.DatabaseClosed(); - } - else { - this._close(); - state.autoOpen = this._options.autoOpen || - state.isBeingOpened; - state.openComplete = false; - state.dbOpenError = null; - } - }; - Dexie.prototype.delete = function (closeOptions) { - var _this = this; - if (closeOptions === void 0) { closeOptions = { disableAutoOpen: true }; } - var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== 'object'; - var state = this._state; - return new DexiePromise(function (resolve, reject) { - var doDelete = function () { - _this.close(closeOptions); - var req = _this._deps.indexedDB.deleteDatabase(_this.name); - req.onsuccess = wrap(function () { - _onDatabaseDeleted(_this._deps, _this.name); - resolve(); - }); - req.onerror = eventRejectHandler(reject); - req.onblocked = _this._fireOnBlocked; - }; - if (hasInvalidArguments) - throw new exceptions.InvalidArgument("Invalid closeOptions argument to db.delete()"); - if (state.isBeingOpened) { - state.dbReadyPromise.then(doDelete); - } - else { - doDelete(); - } - }); - }; - Dexie.prototype.backendDB = function () { - return this.idbdb; - }; - Dexie.prototype.isOpen = function () { - return this.idbdb !== null; - }; - Dexie.prototype.hasBeenClosed = function () { - var dbOpenError = this._state.dbOpenError; - return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); - }; - Dexie.prototype.hasFailed = function () { - return this._state.dbOpenError !== null; - }; - Dexie.prototype.dynamicallyOpened = function () { - return this._state.autoSchema; - }; - Object.defineProperty(Dexie.prototype, "tables", { - get: function () { - var _this = this; - return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); - }, - enumerable: false, - configurable: true - }); - Dexie.prototype.transaction = function () { - var args = extractTransactionArgs.apply(this, arguments); - return this._transaction.apply(this, args); - }; - Dexie.prototype._transaction = function (mode, tables, scopeFunc) { - var _this = this; - var parentTransaction = PSD.trans; - if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) - parentTransaction = null; - var onlyIfCompatible = mode.indexOf('?') !== -1; - mode = mode.replace('!', '').replace('?', ''); - var idbMode, storeNames; - try { - storeNames = tables.map(function (table) { - var storeName = table instanceof _this.Table ? table.name : table; - if (typeof storeName !== 'string') - throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); - return storeName; - }); - if (mode == "r" || mode === READONLY) - idbMode = READONLY; - else if (mode == "rw" || mode == READWRITE) - idbMode = READWRITE; - else - throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); - if (parentTransaction) { - if (parentTransaction.mode === READONLY && idbMode === READWRITE) { - if (onlyIfCompatible) { - parentTransaction = null; - } - else - throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); - } - if (parentTransaction) { - storeNames.forEach(function (storeName) { - if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { - if (onlyIfCompatible) { - parentTransaction = null; - } - else - throw new exceptions.SubTransaction("Table " + storeName + - " not included in parent transaction."); - } - }); - } - if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { - parentTransaction = null; - } - } - } - catch (e) { - return parentTransaction ? - parentTransaction._promise(null, function (_, reject) { reject(e); }) : - rejection(e); - } - var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); - return (parentTransaction ? - parentTransaction._promise(idbMode, enterTransaction, "lock") : - PSD.trans ? - usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : - this._whenReady(enterTransaction)); - }; - Dexie.prototype.table = function (tableName) { - if (!hasOwn(this._allTables, tableName)) { - throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); - } - return this._allTables[tableName]; - }; - return Dexie; - }()); - - var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol - ? Symbol.observable - : "@@observable"; - var Observable = (function () { - function Observable(subscribe) { - this._subscribe = subscribe; - } - Observable.prototype.subscribe = function (x, error, complete) { - return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); - }; - Observable.prototype[symbolObservable] = function () { - return this; - }; - return Observable; - }()); - - var domDeps; - try { - domDeps = { - indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, - IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange - }; - } - catch (e) { - domDeps = { indexedDB: null, IDBKeyRange: null }; - } - - function liveQuery(querier) { - var hasValue = false; - var currentValue; - var observable = new Observable(function (observer) { - var scopeFuncIsAsync = isAsyncFunction(querier); - function execute(ctx) { - var wasRootExec = beginMicroTickScope(); - try { - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var rv = newScope(querier, ctx); - if (scopeFuncIsAsync) { - rv = rv.finally(decrementExpectedAwaits); - } - return rv; - } - finally { - wasRootExec && endMicroTickScope(); - } - } - var closed = false; - var abortController; - var accumMuts = {}; - var currentObs = {}; - var subscription = { - get closed() { - return closed; - }, - unsubscribe: function () { - if (closed) - return; - closed = true; - if (abortController) - abortController.abort(); - if (startedListening) - globalEvents.storagemutated.unsubscribe(mutationListener); - }, - }; - observer.start && observer.start(subscription); - var startedListening = false; - var doQuery = function () { return execInGlobalContext(_doQuery); }; - function shouldNotify() { - return obsSetsOverlap(currentObs, accumMuts); - } - var mutationListener = function (parts) { - extendObservabilitySet(accumMuts, parts); - if (shouldNotify()) { - doQuery(); - } - }; - var _doQuery = function () { - if (closed || - !domDeps.indexedDB) - { - return; - } - accumMuts = {}; - var subscr = {}; - if (abortController) - abortController.abort(); - abortController = new AbortController(); - var ctx = { - subscr: subscr, - signal: abortController.signal, - requery: doQuery, - querier: querier, - trans: null - }; - var ret = execute(ctx); - Promise.resolve(ret).then(function (result) { - hasValue = true; - currentValue = result; - if (closed || ctx.signal.aborted) { - return; - } - accumMuts = {}; - currentObs = subscr; - if (!objectIsEmpty(currentObs) && !startedListening) { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); - startedListening = true; - } - execInGlobalContext(function () { return !closed && observer.next && observer.next(result); }); - }, function (err) { - hasValue = false; - if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) { - if (!closed) - execInGlobalContext(function () { - if (closed) - return; - observer.error && observer.error(err); - }); - } - }); - }; - setTimeout(doQuery, 0); - return subscription; - }); - observable.hasValue = function () { return hasValue; }; - observable.getValue = function () { return currentValue; }; - return observable; - } - - var Dexie = Dexie$1; - props(Dexie, __assign(__assign({}, fullNameExceptions), { - delete: function (databaseName) { - var db = new Dexie(databaseName, { addons: [] }); - return db.delete(); - }, - exists: function (name) { - return new Dexie(name, { addons: [] }).open().then(function (db) { - db.close(); - return true; - }).catch('NoSuchDatabaseError', function () { return false; }); - }, - getDatabaseNames: function (cb) { - try { - return getDatabaseNames(Dexie.dependencies).then(cb); - } - catch (_a) { - return rejection(new exceptions.MissingAPI()); - } - }, - defineClass: function () { - function Class(content) { - extend(this, content); - } - return Class; - }, ignoreTransaction: function (scopeFunc) { - return PSD.trans ? - usePSD(PSD.transless, scopeFunc) : - scopeFunc(); - }, vip: vip, async: function (generatorFn) { - return function () { - try { - var rv = awaitIterator(generatorFn.apply(this, arguments)); - if (!rv || typeof rv.then !== 'function') - return DexiePromise.resolve(rv); - return rv; - } - catch (e) { - return rejection(e); - } - }; - }, spawn: function (generatorFn, args, thiz) { - try { - var rv = awaitIterator(generatorFn.apply(thiz, args || [])); - if (!rv || typeof rv.then !== 'function') - return DexiePromise.resolve(rv); - return rv; - } - catch (e) { - return rejection(e); - } - }, - currentTransaction: { - get: function () { return PSD.trans || null; } - }, waitFor: function (promiseOrFunction, optionalTimeout) { - var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? - Dexie.ignoreTransaction(promiseOrFunction) : - promiseOrFunction) - .timeout(optionalTimeout || 60000); - return PSD.trans ? - PSD.trans.waitFor(promise) : - promise; - }, - Promise: DexiePromise, - debug: { - get: function () { return debug; }, - set: function (value) { - setDebug(value); - } - }, - derive: derive, extend: extend, props: props, override: override, - Events: Events, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, - getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, - minKey: minKey, - addons: [], - connections: connections, - errnames: errnames, - dependencies: domDeps, cache: cache, - semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.') - .map(function (n) { return parseInt(n); }) - .reduce(function (p, c, i) { return p + (c / Math.pow(10, i * 2)); }) })); - Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); - - if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { - if (!propagatingLocally) { - var event_1; - event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { - detail: updatedParts - }); - propagatingLocally = true; - dispatchEvent(event_1); - propagatingLocally = false; - } - }); - addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { - var detail = _a.detail; - if (!propagatingLocally) { - propagateLocally(detail); - } - }); - } - function propagateLocally(updateParts) { - var wasMe = propagatingLocally; - try { - propagatingLocally = true; - globalEvents.storagemutated.fire(updateParts); - signalSubscribersNow(updateParts, true); - } - finally { - propagatingLocally = wasMe; - } - } - var propagatingLocally = false; - - var bc; - var createBC = function () { }; - if (typeof BroadcastChannel !== 'undefined') { - createBC = function () { - bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); - bc.onmessage = function (ev) { return ev.data && propagateLocally(ev.data); }; - }; - createBC(); - if (typeof bc.unref === 'function') { - bc.unref(); - } - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { - if (!propagatingLocally) { - bc.postMessage(changedParts); - } - }); - } - - if (typeof addEventListener !== 'undefined') { - addEventListener('pagehide', function (event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug('Dexie: handling persisted pagehide'); - bc === null || bc === void 0 ? void 0 : bc.close(); - for (var _i = 0, connections_1 = connections; _i < connections_1.length; _i++) { - var db = connections_1[_i]; - db.close({ disableAutoOpen: false }); - } - } - }); - addEventListener('pageshow', function (event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug('Dexie: handling persisted pageshow'); - createBC(); - propagateLocally({ all: new RangeSet(-Infinity, [[]]) }); - } - }); - } - - function replacePrefix(a, b) { - return new PropModification({ replacePrefix: [a, b] }); - } - - DexiePromise.rejectionMapper = mapError; - setDebug(debug); - - var namedExports = /*#__PURE__*/Object.freeze({ - __proto__: null, - Dexie: Dexie$1, - liveQuery: liveQuery, - Entity: Entity, - cmp: cmp, - PropModSymbol: PropModSymbol, - PropModification: PropModification, - replacePrefix: replacePrefix, - 'default': Dexie$1, - RangeSet: RangeSet, - mergeRanges: mergeRanges, - rangesOverlap: rangesOverlap - }); - - __assign(Dexie$1, namedExports, { default: Dexie$1 }); - - return Dexie$1; - -})); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/BehaviorSubject.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/BehaviorSubject.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ BehaviorSubject: () => (/* binding */ BehaviorSubject) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Subject */ "./node_modules/rxjs/dist/esm5/internal/Subject.js"); - - -var BehaviorSubject = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(BehaviorSubject, _super); - function BehaviorSubject(_value) { - var _this = _super.call(this) || this; - _this._value = _value; - return _this; - } - Object.defineProperty(BehaviorSubject.prototype, "value", { - get: function () { - return this.getValue(); - }, - enumerable: false, - configurable: true - }); - BehaviorSubject.prototype._subscribe = function (subscriber) { - var subscription = _super.prototype._subscribe.call(this, subscriber); - !subscription.closed && subscriber.next(this._value); - return subscription; - }; - BehaviorSubject.prototype.getValue = function () { - var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value; - if (hasError) { - throw thrownError; - } - this._throwIfClosed(); - return _value; - }; - BehaviorSubject.prototype.next = function (value) { - _super.prototype.next.call(this, (this._value = value)); - }; - return BehaviorSubject; -}(_Subject__WEBPACK_IMPORTED_MODULE_1__.Subject)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/NotificationFactories.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/NotificationFactories.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ COMPLETE_NOTIFICATION: () => (/* binding */ COMPLETE_NOTIFICATION), -/* harmony export */ createNotification: () => (/* binding */ createNotification), -/* harmony export */ errorNotification: () => (/* binding */ errorNotification), -/* harmony export */ nextNotification: () => (/* binding */ nextNotification) -/* harmony export */ }); -var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })(); -function errorNotification(error) { - return createNotification('E', undefined, error); -} -function nextNotification(value) { - return createNotification('N', value, undefined); -} -function createNotification(kind, value, error) { - return { - kind: kind, - value: value, - error: error, - }; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/Observable.js": -/*!************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/Observable.js ***! - \************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Observable: () => (/* binding */ Observable) -/* harmony export */ }); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscriber */ "./node_modules/rxjs/dist/esm5/internal/Subscriber.js"); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/dist/esm5/internal/Subscription.js"); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./symbol/observable */ "./node_modules/rxjs/dist/esm5/internal/symbol/observable.js"); -/* harmony import */ var _util_pipe__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/pipe */ "./node_modules/rxjs/dist/esm5/internal/util/pipe.js"); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./config */ "./node_modules/rxjs/dist/esm5/internal/config.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/errorContext */ "./node_modules/rxjs/dist/esm5/internal/util/errorContext.js"); - - - - - - - -var Observable = (function () { - function Observable(subscribe) { - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var _this = this; - var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new _Subscriber__WEBPACK_IMPORTED_MODULE_0__.SafeSubscriber(observerOrNext, error, complete); - (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_1__.errorContext)(function () { - var _a = _this, operator = _a.operator, source = _a.source; - subscriber.add(operator - ? - operator.call(subscriber, source) - : source - ? - _this._subscribe(subscriber) - : - _this._trySubscribe(subscriber)); - }); - return subscriber; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - sink.error(err); - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscriber = new _Subscriber__WEBPACK_IMPORTED_MODULE_0__.SafeSubscriber({ - next: function (value) { - try { - next(value); - } - catch (err) { - reject(err); - subscriber.unsubscribe(); - } - }, - error: reject, - complete: resolve, - }); - _this.subscribe(subscriber); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var _a; - return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber); - }; - Observable.prototype[_symbol_observable__WEBPACK_IMPORTED_MODULE_2__.observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - return (0,_util_pipe__WEBPACK_IMPORTED_MODULE_3__.pipeFromArray)(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; -}()); - -function getPromiseCtor(promiseCtor) { - var _a; - return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : _config__WEBPACK_IMPORTED_MODULE_4__.config.Promise) !== null && _a !== void 0 ? _a : Promise; -} -function isObserver(value) { - return value && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.next) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.error) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_5__.isFunction)(value.complete); -} -function isSubscriber(value) { - return (value && value instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__.Subscriber) || (isObserver(value) && (0,_Subscription__WEBPACK_IMPORTED_MODULE_6__.isSubscription)(value)); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/Scheduler.js": -/*!***********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/Scheduler.js ***! - \***********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Scheduler: () => (/* binding */ Scheduler) -/* harmony export */ }); -/* harmony import */ var _scheduler_dateTimestampProvider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scheduler/dateTimestampProvider */ "./node_modules/rxjs/dist/esm5/internal/scheduler/dateTimestampProvider.js"); - -var Scheduler = (function () { - function Scheduler(schedulerActionCtor, now) { - if (now === void 0) { now = Scheduler.now; } - this.schedulerActionCtor = schedulerActionCtor; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { delay = 0; } - return new this.schedulerActionCtor(this, work).schedule(state, delay); - }; - Scheduler.now = _scheduler_dateTimestampProvider__WEBPACK_IMPORTED_MODULE_0__.dateTimestampProvider.now; - return Scheduler; -}()); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/Subject.js": -/*!*********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/Subject.js ***! - \*********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AnonymousSubject: () => (/* binding */ AnonymousSubject), -/* harmony export */ Subject: () => (/* binding */ Subject) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/dist/esm5/internal/Subscription.js"); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/ObjectUnsubscribedError */ "./node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js"); -/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./util/arrRemove */ "./node_modules/rxjs/dist/esm5/internal/util/arrRemove.js"); -/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/errorContext */ "./node_modules/rxjs/dist/esm5/internal/util/errorContext.js"); - - - - - - -var Subject = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.closed = false; - _this.currentObservers = null; - _this.observers = []; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype._throwIfClosed = function () { - if (this.closed) { - throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_1__.ObjectUnsubscribedError(); - } - }; - Subject.prototype.next = function (value) { - var _this = this; - (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(function () { - var e_1, _a; - _this._throwIfClosed(); - if (!_this.isStopped) { - if (!_this.currentObservers) { - _this.currentObservers = Array.from(_this.observers); - } - try { - for (var _b = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) { - var observer = _c.value; - observer.next(value); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - } - }); - }; - Subject.prototype.error = function (err) { - var _this = this; - (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(function () { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.hasError = _this.isStopped = true; - _this.thrownError = err; - var observers = _this.observers; - while (observers.length) { - observers.shift().error(err); - } - } - }); - }; - Subject.prototype.complete = function () { - var _this = this; - (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_2__.errorContext)(function () { - _this._throwIfClosed(); - if (!_this.isStopped) { - _this.isStopped = true; - var observers = _this.observers; - while (observers.length) { - observers.shift().complete(); - } - } - }); - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = this.closed = true; - this.observers = this.currentObservers = null; - }; - Object.defineProperty(Subject.prototype, "observed", { - get: function () { - var _a; - return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0; - }, - enumerable: false, - configurable: true - }); - Subject.prototype._trySubscribe = function (subscriber) { - this._throwIfClosed(); - return _super.prototype._trySubscribe.call(this, subscriber); - }; - Subject.prototype._subscribe = function (subscriber) { - this._throwIfClosed(); - this._checkFinalizedStatuses(subscriber); - return this._innerSubscribe(subscriber); - }; - Subject.prototype._innerSubscribe = function (subscriber) { - var _this = this; - var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers; - if (hasError || isStopped) { - return _Subscription__WEBPACK_IMPORTED_MODULE_3__.EMPTY_SUBSCRIPTION; - } - this.currentObservers = null; - observers.push(subscriber); - return new _Subscription__WEBPACK_IMPORTED_MODULE_3__.Subscription(function () { - _this.currentObservers = null; - (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_4__.arrRemove)(observers, subscriber); - }); - }; - Subject.prototype._checkFinalizedStatuses = function (subscriber) { - var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped; - if (hasError) { - subscriber.error(thrownError); - } - else if (isStopped) { - subscriber.complete(); - } - }; - Subject.prototype.asObservable = function () { - var observable = new _Observable__WEBPACK_IMPORTED_MODULE_5__.Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; -}(_Observable__WEBPACK_IMPORTED_MODULE_5__.Observable)); - -var AnonymousSubject = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value); - }; - AnonymousSubject.prototype.error = function (err) { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err); - }; - AnonymousSubject.prototype.complete = function () { - var _a, _b; - (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a); - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var _a, _b; - return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : _Subscription__WEBPACK_IMPORTED_MODULE_3__.EMPTY_SUBSCRIPTION; - }; - return AnonymousSubject; -}(Subject)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/Subscriber.js": -/*!************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/Subscriber.js ***! - \************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EMPTY_OBSERVER: () => (/* binding */ EMPTY_OBSERVER), -/* harmony export */ SafeSubscriber: () => (/* binding */ SafeSubscriber), -/* harmony export */ Subscriber: () => (/* binding */ Subscriber) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Subscription */ "./node_modules/rxjs/dist/esm5/internal/Subscription.js"); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./config */ "./node_modules/rxjs/dist/esm5/internal/config.js"); -/* harmony import */ var _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./util/reportUnhandledError */ "./node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js"); -/* harmony import */ var _util_noop__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./util/noop */ "./node_modules/rxjs/dist/esm5/internal/util/noop.js"); -/* harmony import */ var _NotificationFactories__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NotificationFactories */ "./node_modules/rxjs/dist/esm5/internal/NotificationFactories.js"); -/* harmony import */ var _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./scheduler/timeoutProvider */ "./node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js"); -/* harmony import */ var _util_errorContext__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./util/errorContext */ "./node_modules/rxjs/dist/esm5/internal/util/errorContext.js"); - - - - - - - - - -var Subscriber = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(Subscriber, _super); - function Subscriber(destination) { - var _this = _super.call(this) || this; - _this.isStopped = false; - if (destination) { - _this.destination = destination; - if ((0,_Subscription__WEBPACK_IMPORTED_MODULE_1__.isSubscription)(destination)) { - destination.add(_this); - } - } - else { - _this.destination = EMPTY_OBSERVER; - } - return _this; - } - Subscriber.create = function (next, error, complete) { - return new SafeSubscriber(next, error, complete); - }; - Subscriber.prototype.next = function (value) { - if (this.isStopped) { - handleStoppedNotification((0,_NotificationFactories__WEBPACK_IMPORTED_MODULE_2__.nextNotification)(value), this); - } - else { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (this.isStopped) { - handleStoppedNotification((0,_NotificationFactories__WEBPACK_IMPORTED_MODULE_2__.errorNotification)(err), this); - } - else { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (this.isStopped) { - handleStoppedNotification(_NotificationFactories__WEBPACK_IMPORTED_MODULE_2__.COMPLETE_NOTIFICATION, this); - } - else { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (!this.closed) { - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - this.destination = null; - } - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - try { - this.destination.error(err); - } - finally { - this.unsubscribe(); - } - }; - Subscriber.prototype._complete = function () { - try { - this.destination.complete(); - } - finally { - this.unsubscribe(); - } - }; - return Subscriber; -}(_Subscription__WEBPACK_IMPORTED_MODULE_1__.Subscription)); - -var _bind = Function.prototype.bind; -function bind(fn, thisArg) { - return _bind.call(fn, thisArg); -} -var ConsumerObserver = (function () { - function ConsumerObserver(partialObserver) { - this.partialObserver = partialObserver; - } - ConsumerObserver.prototype.next = function (value) { - var partialObserver = this.partialObserver; - if (partialObserver.next) { - try { - partialObserver.next(value); - } - catch (error) { - handleUnhandledError(error); - } - } - }; - ConsumerObserver.prototype.error = function (err) { - var partialObserver = this.partialObserver; - if (partialObserver.error) { - try { - partialObserver.error(err); - } - catch (error) { - handleUnhandledError(error); - } - } - else { - handleUnhandledError(err); - } - }; - ConsumerObserver.prototype.complete = function () { - var partialObserver = this.partialObserver; - if (partialObserver.complete) { - try { - partialObserver.complete(); - } - catch (error) { - handleUnhandledError(error); - } - } - }; - return ConsumerObserver; -}()); -var SafeSubscriber = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(SafeSubscriber, _super); - function SafeSubscriber(observerOrNext, error, complete) { - var _this = _super.call(this) || this; - var partialObserver; - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_3__.isFunction)(observerOrNext) || !observerOrNext) { - partialObserver = { - next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined), - error: error !== null && error !== void 0 ? error : undefined, - complete: complete !== null && complete !== void 0 ? complete : undefined, - }; - } - else { - var context_1; - if (_this && _config__WEBPACK_IMPORTED_MODULE_4__.config.useDeprecatedNextContext) { - context_1 = Object.create(observerOrNext); - context_1.unsubscribe = function () { return _this.unsubscribe(); }; - partialObserver = { - next: observerOrNext.next && bind(observerOrNext.next, context_1), - error: observerOrNext.error && bind(observerOrNext.error, context_1), - complete: observerOrNext.complete && bind(observerOrNext.complete, context_1), - }; - } - else { - partialObserver = observerOrNext; - } - } - _this.destination = new ConsumerObserver(partialObserver); - return _this; - } - return SafeSubscriber; -}(Subscriber)); - -function handleUnhandledError(error) { - if (_config__WEBPACK_IMPORTED_MODULE_4__.config.useDeprecatedSynchronousErrorHandling) { - (0,_util_errorContext__WEBPACK_IMPORTED_MODULE_5__.captureError)(error); - } - else { - (0,_util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_6__.reportUnhandledError)(error); - } -} -function defaultErrorHandler(err) { - throw err; -} -function handleStoppedNotification(notification, subscriber) { - var onStoppedNotification = _config__WEBPACK_IMPORTED_MODULE_4__.config.onStoppedNotification; - onStoppedNotification && _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_7__.timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); }); -} -var EMPTY_OBSERVER = { - closed: true, - next: _util_noop__WEBPACK_IMPORTED_MODULE_8__.noop, - error: defaultErrorHandler, - complete: _util_noop__WEBPACK_IMPORTED_MODULE_8__.noop, -}; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/Subscription.js": -/*!**************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/Subscription.js ***! - \**************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EMPTY_SUBSCRIPTION: () => (/* binding */ EMPTY_SUBSCRIPTION), -/* harmony export */ Subscription: () => (/* binding */ Subscription), -/* harmony export */ isSubscription: () => (/* binding */ isSubscription) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util/UnsubscriptionError */ "./node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js"); -/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./util/arrRemove */ "./node_modules/rxjs/dist/esm5/internal/util/arrRemove.js"); - - - - -var Subscription = (function () { - function Subscription(initialTeardown) { - this.initialTeardown = initialTeardown; - this.closed = false; - this._parentage = null; - this._finalizers = null; - } - Subscription.prototype.unsubscribe = function () { - var e_1, _a, e_2, _b; - var errors; - if (!this.closed) { - this.closed = true; - var _parentage = this._parentage; - if (_parentage) { - this._parentage = null; - if (Array.isArray(_parentage)) { - try { - for (var _parentage_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) { - var parent_1 = _parentage_1_1.value; - parent_1.remove(this); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1); - } - finally { if (e_1) throw e_1.error; } - } - } - else { - _parentage.remove(this); - } - } - var initialFinalizer = this.initialTeardown; - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(initialFinalizer)) { - try { - initialFinalizer(); - } - catch (e) { - errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_2__.UnsubscriptionError ? e.errors : [e]; - } - } - var _finalizers = this._finalizers; - if (_finalizers) { - this._finalizers = null; - try { - for (var _finalizers_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__values)(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) { - var finalizer = _finalizers_1_1.value; - try { - execFinalizer(finalizer); - } - catch (err) { - errors = errors !== null && errors !== void 0 ? errors : []; - if (err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_2__.UnsubscriptionError) { - errors = (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)((0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(errors)), (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(err.errors)); - } - else { - errors.push(err); - } - } - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1); - } - finally { if (e_2) throw e_2.error; } - } - } - if (errors) { - throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_2__.UnsubscriptionError(errors); - } - } - }; - Subscription.prototype.add = function (teardown) { - var _a; - if (teardown && teardown !== this) { - if (this.closed) { - execFinalizer(teardown); - } - else { - if (teardown instanceof Subscription) { - if (teardown.closed || teardown._hasParent(this)) { - return; - } - teardown._addParent(this); - } - (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown); - } - } - }; - Subscription.prototype._hasParent = function (parent) { - var _parentage = this._parentage; - return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent)); - }; - Subscription.prototype._addParent = function (parent) { - var _parentage = this._parentage; - this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent; - }; - Subscription.prototype._removeParent = function (parent) { - var _parentage = this._parentage; - if (_parentage === parent) { - this._parentage = null; - } - else if (Array.isArray(_parentage)) { - (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_3__.arrRemove)(_parentage, parent); - } - }; - Subscription.prototype.remove = function (teardown) { - var _finalizers = this._finalizers; - _finalizers && (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_3__.arrRemove)(_finalizers, teardown); - if (teardown instanceof Subscription) { - teardown._removeParent(this); - } - }; - Subscription.EMPTY = (function () { - var empty = new Subscription(); - empty.closed = true; - return empty; - })(); - return Subscription; -}()); - -var EMPTY_SUBSCRIPTION = Subscription.EMPTY; -function isSubscription(value) { - return (value instanceof Subscription || - (value && 'closed' in value && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(value.remove) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(value.add) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(value.unsubscribe))); -} -function execFinalizer(finalizer) { - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(finalizer)) { - finalizer(); - } - else { - finalizer.unsubscribe(); - } -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/config.js": -/*!********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/config.js ***! - \********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ config: () => (/* binding */ config) -/* harmony export */ }); -var config = { - onUnhandledError: null, - onStoppedNotification: null, - Promise: undefined, - useDeprecatedSynchronousErrorHandling: false, - useDeprecatedNextContext: false, -}; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/firstValueFrom.js": -/*!****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/firstValueFrom.js ***! - \****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ firstValueFrom: () => (/* binding */ firstValueFrom) -/* harmony export */ }); -/* harmony import */ var _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./util/EmptyError */ "./node_modules/rxjs/dist/esm5/internal/util/EmptyError.js"); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Subscriber */ "./node_modules/rxjs/dist/esm5/internal/Subscriber.js"); - - -function firstValueFrom(source, config) { - var hasConfig = typeof config === 'object'; - return new Promise(function (resolve, reject) { - var subscriber = new _Subscriber__WEBPACK_IMPORTED_MODULE_0__.SafeSubscriber({ - next: function (value) { - resolve(value); - subscriber.unsubscribe(); - }, - error: reject, - complete: function () { - if (hasConfig) { - resolve(config.defaultValue); - } - else { - reject(new _util_EmptyError__WEBPACK_IMPORTED_MODULE_1__.EmptyError()); - } - }, - }); - source.subscribe(subscriber); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/combineLatest.js": -/*!**************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/combineLatest.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ combineLatest: () => (/* binding */ combineLatest), -/* harmony export */ combineLatestInit: () => (/* binding */ combineLatestInit) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/argsArgArrayOrObject */ "./node_modules/rxjs/dist/esm5/internal/util/argsArgArrayOrObject.js"); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/dist/esm5/internal/observable/from.js"); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/dist/esm5/internal/util/identity.js"); -/* harmony import */ var _util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/mapOneOrManyArgs */ "./node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js"); -/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ "./node_modules/rxjs/dist/esm5/internal/util/args.js"); -/* harmony import */ var _util_createObject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/createObject */ "./node_modules/rxjs/dist/esm5/internal/util/createObject.js"); -/* harmony import */ var _operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../operators/OperatorSubscriber */ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js"); -/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/executeSchedule */ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js"); - - - - - - - - - -function combineLatest() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args); - var resultSelector = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popResultSelector)(args); - var _a = (0,_util_argsArgArrayOrObject__WEBPACK_IMPORTED_MODULE_1__.argsArgArrayOrObject)(args), observables = _a.args, keys = _a.keys; - if (observables.length === 0) { - return (0,_from__WEBPACK_IMPORTED_MODULE_2__.from)([], scheduler); - } - var result = new _Observable__WEBPACK_IMPORTED_MODULE_3__.Observable(combineLatestInit(observables, scheduler, keys - ? - function (values) { return (0,_util_createObject__WEBPACK_IMPORTED_MODULE_4__.createObject)(keys, values); } - : - _util_identity__WEBPACK_IMPORTED_MODULE_5__.identity)); - return resultSelector ? result.pipe((0,_util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_6__.mapOneOrManyArgs)(resultSelector)) : result; -} -function combineLatestInit(observables, scheduler, valueTransform) { - if (valueTransform === void 0) { valueTransform = _util_identity__WEBPACK_IMPORTED_MODULE_5__.identity; } - return function (subscriber) { - maybeSchedule(scheduler, function () { - var length = observables.length; - var values = new Array(length); - var active = length; - var remainingFirstValues = length; - var _loop_1 = function (i) { - maybeSchedule(scheduler, function () { - var source = (0,_from__WEBPACK_IMPORTED_MODULE_2__.from)(observables[i], scheduler); - var hasFirstValue = false; - source.subscribe((0,_operators_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_7__.createOperatorSubscriber)(subscriber, function (value) { - values[i] = value; - if (!hasFirstValue) { - hasFirstValue = true; - remainingFirstValues--; - } - if (!remainingFirstValues) { - subscriber.next(valueTransform(values.slice())); - } - }, function () { - if (!--active) { - subscriber.complete(); - } - })); - }, subscriber); - }; - for (var i = 0; i < length; i++) { - _loop_1(i); - } - }, subscriber); - }; -} -function maybeSchedule(scheduler, execute, subscription) { - if (scheduler) { - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_8__.executeSchedule)(subscription, scheduler, execute); - } - else { - execute(); - } -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/empty.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/empty.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EMPTY: () => (/* binding */ EMPTY), -/* harmony export */ empty: () => (/* binding */ empty) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); - -var EMPTY = new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { return subscriber.complete(); }); -function empty(scheduler) { - return scheduler ? emptyScheduled(scheduler) : EMPTY; -} -function emptyScheduled(scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/from.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/from.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ from: () => (/* binding */ from) -/* harmony export */ }); -/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduled/scheduled */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js"); -/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); - - -function from(input, scheduler) { - return scheduler ? (0,_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_0__.scheduled)(input, scheduler) : (0,_innerFrom__WEBPACK_IMPORTED_MODULE_1__.innerFrom)(input); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/fromEvent.js": -/*!**********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/fromEvent.js ***! - \**********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ fromEvent: () => (/* binding */ fromEvent) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _operators_mergeMap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../operators/mergeMap */ "./node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js"); -/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isArrayLike */ "./node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/mapOneOrManyArgs */ "./node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js"); - - - - - - - -var nodeEventEmitterMethods = ['addListener', 'removeListener']; -var eventTargetMethods = ['addEventListener', 'removeEventListener']; -var jqueryMethods = ['on', 'off']; -function fromEvent(target, eventName, options, resultSelector) { - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(options)) { - resultSelector = options; - options = undefined; - } - if (resultSelector) { - return fromEvent(target, eventName, options).pipe((0,_util_mapOneOrManyArgs__WEBPACK_IMPORTED_MODULE_1__.mapOneOrManyArgs)(resultSelector)); - } - var _a = (0,tslib__WEBPACK_IMPORTED_MODULE_2__.__read)(isEventTarget(target) - ? eventTargetMethods.map(function (methodName) { return function (handler) { return target[methodName](eventName, handler, options); }; }) - : - isNodeStyleEventEmitter(target) - ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName)) - : isJQueryStyleEventEmitter(target) - ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName)) - : [], 2), add = _a[0], remove = _a[1]; - if (!add) { - if ((0,_util_isArrayLike__WEBPACK_IMPORTED_MODULE_3__.isArrayLike)(target)) { - return (0,_operators_mergeMap__WEBPACK_IMPORTED_MODULE_4__.mergeMap)(function (subTarget) { return fromEvent(subTarget, eventName, options); })((0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_5__.innerFrom)(target)); - } - } - if (!add) { - throw new TypeError('Invalid event target'); - } - return new _Observable__WEBPACK_IMPORTED_MODULE_6__.Observable(function (subscriber) { - var handler = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return subscriber.next(1 < args.length ? args : args[0]); - }; - add(handler); - return function () { return remove(handler); }; - }); -} -function toCommonHandlerRegistry(target, eventName) { - return function (methodName) { return function (handler) { return target[methodName](eventName, handler); }; }; -} -function isNodeStyleEventEmitter(target) { - return (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.addListener) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.removeListener); -} -function isJQueryStyleEventEmitter(target) { - return (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.on) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.off); -} -function isEventTarget(target) { - return (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.addEventListener) && (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(target.removeEventListener); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js": -/*!**********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js ***! - \**********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ fromArrayLike: () => (/* binding */ fromArrayLike), -/* harmony export */ fromAsyncIterable: () => (/* binding */ fromAsyncIterable), -/* harmony export */ fromInteropObservable: () => (/* binding */ fromInteropObservable), -/* harmony export */ fromIterable: () => (/* binding */ fromIterable), -/* harmony export */ fromPromise: () => (/* binding */ fromPromise), -/* harmony export */ fromReadableStreamLike: () => (/* binding */ fromReadableStreamLike), -/* harmony export */ innerFrom: () => (/* binding */ innerFrom) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isArrayLike */ "./node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js"); -/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isPromise */ "./node_modules/rxjs/dist/esm5/internal/util/isPromise.js"); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isInteropObservable */ "./node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js"); -/* harmony import */ var _util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isAsyncIterable */ "./node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js"); -/* harmony import */ var _util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/throwUnobservableError */ "./node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js"); -/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/isIterable */ "./node_modules/rxjs/dist/esm5/internal/util/isIterable.js"); -/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/isReadableStreamLike */ "./node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/reportUnhandledError */ "./node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js"); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/dist/esm5/internal/symbol/observable.js"); - - - - - - - - - - - - -function innerFrom(input) { - if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable) { - return input; - } - if (input != null) { - if ((0,_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_1__.isInteropObservable)(input)) { - return fromInteropObservable(input); - } - if ((0,_util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__.isArrayLike)(input)) { - return fromArrayLike(input); - } - if ((0,_util_isPromise__WEBPACK_IMPORTED_MODULE_3__.isPromise)(input)) { - return fromPromise(input); - } - if ((0,_util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_4__.isAsyncIterable)(input)) { - return fromAsyncIterable(input); - } - if ((0,_util_isIterable__WEBPACK_IMPORTED_MODULE_5__.isIterable)(input)) { - return fromIterable(input); - } - if ((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__.isReadableStreamLike)(input)) { - return fromReadableStreamLike(input); - } - } - throw (0,_util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_7__.createInvalidObservableTypeError)(input); -} -function fromInteropObservable(obj) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - var obs = obj[_symbol_observable__WEBPACK_IMPORTED_MODULE_8__.observable](); - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_9__.isFunction)(obs.subscribe)) { - return obs.subscribe(subscriber); - } - throw new TypeError('Provided object does not correctly implement Symbol.observable'); - }); -} -function fromArrayLike(array) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - for (var i = 0; i < array.length && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }); -} -function fromPromise(promise) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - promise - .then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, _util_reportUnhandledError__WEBPACK_IMPORTED_MODULE_10__.reportUnhandledError); - }); -} -function fromIterable(iterable) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - var e_1, _a; - try { - for (var iterable_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__values)(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) { - var value = iterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1); - } - finally { if (e_1) throw e_1.error; } - } - subscriber.complete(); - }); -} -function fromAsyncIterable(asyncIterable) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); }); - }); -} -function fromReadableStreamLike(readableStream) { - return fromAsyncIterable((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_6__.readableStreamLikeToAsyncGenerator)(readableStream)); -} -function process(asyncIterable, subscriber) { - var asyncIterable_1, asyncIterable_1_1; - var e_2, _a; - return (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__awaiter)(this, void 0, void 0, function () { - var value, e_2_1; - return (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__generator)(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 5, 6, 11]); - asyncIterable_1 = (0,tslib__WEBPACK_IMPORTED_MODULE_11__.__asyncValues)(asyncIterable); - _b.label = 1; - case 1: return [4, asyncIterable_1.next()]; - case 2: - if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4]; - value = asyncIterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return [2]; - } - _b.label = 3; - case 3: return [3, 1]; - case 4: return [3, 11]; - case 5: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3, 11]; - case 6: - _b.trys.push([6, , 9, 10]); - if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8]; - return [4, _a.call(asyncIterable_1)]; - case 7: - _b.sent(); - _b.label = 8; - case 8: return [3, 10]; - case 9: - if (e_2) throw e_2.error; - return [7]; - case 10: return [7]; - case 11: - subscriber.complete(); - return [2]; - } - }); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/merge.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/merge.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ merge: () => (/* binding */ merge) -/* harmony export */ }); -/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../operators/mergeAll */ "./node_modules/rxjs/dist/esm5/internal/operators/mergeAll.js"); -/* harmony import */ var _innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./empty */ "./node_modules/rxjs/dist/esm5/internal/observable/empty.js"); -/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ "./node_modules/rxjs/dist/esm5/internal/util/args.js"); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/dist/esm5/internal/observable/from.js"); - - - - - -function merge() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args); - var concurrent = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popNumber)(args, Infinity); - var sources = args; - return !sources.length - ? - _empty__WEBPACK_IMPORTED_MODULE_1__.EMPTY - : sources.length === 1 - ? - (0,_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(sources[0]) - : - (0,_operators_mergeAll__WEBPACK_IMPORTED_MODULE_3__.mergeAll)(concurrent)((0,_from__WEBPACK_IMPORTED_MODULE_4__.from)(sources, scheduler)); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/of.js": -/*!***************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/of.js ***! - \***************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ of: () => (/* binding */ of) -/* harmony export */ }); -/* harmony import */ var _util_args__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/args */ "./node_modules/rxjs/dist/esm5/internal/util/args.js"); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./from */ "./node_modules/rxjs/dist/esm5/internal/observable/from.js"); - - -function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = (0,_util_args__WEBPACK_IMPORTED_MODULE_0__.popScheduler)(args); - return (0,_from__WEBPACK_IMPORTED_MODULE_1__.from)(args, scheduler); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/throwError.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/throwError.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ throwError: () => (/* binding */ throwError) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - - -function throwError(errorOrErrorFactory, scheduler) { - var errorFactory = (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(errorOrErrorFactory) ? errorOrErrorFactory : function () { return errorOrErrorFactory; }; - var init = function (subscriber) { return subscriber.error(errorFactory()); }; - return new _Observable__WEBPACK_IMPORTED_MODULE_1__.Observable(scheduler ? function (subscriber) { return scheduler.schedule(init, 0, subscriber); } : init); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/observable/timer.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/observable/timer.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ timer: () => (/* binding */ timer) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/async */ "./node_modules/rxjs/dist/esm5/internal/scheduler/async.js"); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isScheduler */ "./node_modules/rxjs/dist/esm5/internal/util/isScheduler.js"); -/* harmony import */ var _util_isDate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isDate */ "./node_modules/rxjs/dist/esm5/internal/util/isDate.js"); - - - - -function timer(dueTime, intervalOrScheduler, scheduler) { - if (dueTime === void 0) { dueTime = 0; } - if (scheduler === void 0) { scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_0__.async; } - var intervalDuration = -1; - if (intervalOrScheduler != null) { - if ((0,_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__.isScheduler)(intervalOrScheduler)) { - scheduler = intervalOrScheduler; - } - else { - intervalDuration = intervalOrScheduler; - } - } - return new _Observable__WEBPACK_IMPORTED_MODULE_2__.Observable(function (subscriber) { - var due = (0,_util_isDate__WEBPACK_IMPORTED_MODULE_3__.isValidDate)(dueTime) ? +dueTime - scheduler.now() : dueTime; - if (due < 0) { - due = 0; - } - var n = 0; - return scheduler.schedule(function () { - if (!subscriber.closed) { - subscriber.next(n++); - if (0 <= intervalDuration) { - this.schedule(undefined, intervalDuration); - } - else { - subscriber.complete(); - } - } - }, due); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js": -/*!******************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ OperatorSubscriber: () => (/* binding */ OperatorSubscriber), -/* harmony export */ createOperatorSubscriber: () => (/* binding */ createOperatorSubscriber) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/dist/esm5/internal/Subscriber.js"); - - -function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) { - return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize); -} -var OperatorSubscriber = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(OperatorSubscriber, _super); - function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) { - var _this = _super.call(this, destination) || this; - _this.onFinalize = onFinalize; - _this.shouldUnsubscribe = shouldUnsubscribe; - _this._next = onNext - ? function (value) { - try { - onNext(value); - } - catch (err) { - destination.error(err); - } - } - : _super.prototype._next; - _this._error = onError - ? function (err) { - try { - onError(err); - } - catch (err) { - destination.error(err); - } - finally { - this.unsubscribe(); - } - } - : _super.prototype._error; - _this._complete = onComplete - ? function () { - try { - onComplete(); - } - catch (err) { - destination.error(err); - } - finally { - this.unsubscribe(); - } - } - : _super.prototype._complete; - return _this; - } - OperatorSubscriber.prototype.unsubscribe = function () { - var _a; - if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) { - var closed_1 = this.closed; - _super.prototype.unsubscribe.call(this); - !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this)); - } - }; - return OperatorSubscriber; -}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__.Subscriber)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/filter.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/filter.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ filter: () => (/* binding */ filter) -/* harmony export */ }); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); -/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js"); - - -function filter(predicate, thisArg) { - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)(function (source, subscriber) { - var index = 0; - source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); })); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/map.js": -/*!***************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/map.js ***! - \***************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ map: () => (/* binding */ map) -/* harmony export */ }); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); -/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js"); - - -function map(project, thisArg) { - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)(function (source, subscriber) { - var index = 0; - source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, function (value) { - subscriber.next(project.call(thisArg, value, index++)); - })); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/mergeAll.js": -/*!********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/mergeAll.js ***! - \********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ mergeAll: () => (/* binding */ mergeAll) -/* harmony export */ }); -/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mergeMap */ "./node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js"); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/identity */ "./node_modules/rxjs/dist/esm5/internal/util/identity.js"); - - -function mergeAll(concurrent) { - if (concurrent === void 0) { concurrent = Infinity; } - return (0,_mergeMap__WEBPACK_IMPORTED_MODULE_0__.mergeMap)(_util_identity__WEBPACK_IMPORTED_MODULE_1__.identity, concurrent); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/mergeInternals.js": -/*!**************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/mergeInternals.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ mergeInternals: () => (/* binding */ mergeInternals) -/* harmony export */ }); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/executeSchedule */ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js"); -/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js"); - - - -function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) { - var buffer = []; - var active = 0; - var index = 0; - var isComplete = false; - var checkComplete = function () { - if (isComplete && !buffer.length && !active) { - subscriber.complete(); - } - }; - var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); }; - var doInnerSub = function (value) { - expand && subscriber.next(value); - active++; - var innerComplete = false; - (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(project(value, index++)).subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, function (innerValue) { - onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue); - if (expand) { - outerNext(innerValue); - } - else { - subscriber.next(innerValue); - } - }, function () { - innerComplete = true; - }, undefined, function () { - if (innerComplete) { - try { - active--; - var _loop_1 = function () { - var bufferedValue = buffer.shift(); - if (innerSubScheduler) { - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); }); - } - else { - doInnerSub(bufferedValue); - } - }; - while (buffer.length && active < concurrent) { - _loop_1(); - } - checkComplete(); - } - catch (err) { - subscriber.error(err); - } - } - })); - }; - source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, outerNext, function () { - isComplete = true; - checkComplete(); - })); - return function () { - additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer(); - }; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js": -/*!********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/mergeMap.js ***! - \********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ mergeMap: () => (/* binding */ mergeMap) -/* harmony export */ }); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./map */ "./node_modules/rxjs/dist/esm5/internal/operators/map.js"); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); -/* harmony import */ var _mergeInternals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./mergeInternals */ "./node_modules/rxjs/dist/esm5/internal/operators/mergeInternals.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - - - - - -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { concurrent = Infinity; } - if ((0,_util_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(resultSelector)) { - return mergeMap(function (a, i) { return (0,_map__WEBPACK_IMPORTED_MODULE_1__.map)(function (b, ii) { return resultSelector(a, b, i, ii); })((0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_2__.innerFrom)(project(a, i))); }, concurrent); - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_3__.operate)(function (source, subscriber) { return (0,_mergeInternals__WEBPACK_IMPORTED_MODULE_4__.mergeInternals)(source, subscriber, project, concurrent); }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/observeOn.js": -/*!*********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/observeOn.js ***! - \*********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ observeOn: () => (/* binding */ observeOn) -/* harmony export */ }); -/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/executeSchedule */ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js"); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); -/* harmony import */ var _OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./OperatorSubscriber */ "./node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js"); - - - -function observeOn(scheduler, delay) { - if (delay === void 0) { delay = 0; } - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)(function (source, subscriber) { - source.subscribe((0,_OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.createOperatorSubscriber)(subscriber, function (value) { return (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_2__.executeSchedule)(subscriber, scheduler, function () { return subscriber.error(err); }, delay); })); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/share.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/share.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ share: () => (/* binding */ share) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Subject */ "./node_modules/rxjs/dist/esm5/internal/Subject.js"); -/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Subscriber */ "./node_modules/rxjs/dist/esm5/internal/Subscriber.js"); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); - - - - - -function share(options) { - if (options === void 0) { options = {}; } - var _a = options.connector, connector = _a === void 0 ? function () { return new _Subject__WEBPACK_IMPORTED_MODULE_0__.Subject(); } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? true : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? true : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? true : _d; - return function (wrapperSource) { - var connection; - var resetConnection; - var subject; - var refCount = 0; - var hasCompleted = false; - var hasErrored = false; - var cancelReset = function () { - resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe(); - resetConnection = undefined; - }; - var reset = function () { - cancelReset(); - connection = subject = undefined; - hasCompleted = hasErrored = false; - }; - var resetAndUnsubscribe = function () { - var conn = connection; - reset(); - conn === null || conn === void 0 ? void 0 : conn.unsubscribe(); - }; - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_1__.operate)(function (source, subscriber) { - refCount++; - if (!hasErrored && !hasCompleted) { - cancelReset(); - } - var dest = (subject = subject !== null && subject !== void 0 ? subject : connector()); - subscriber.add(function () { - refCount--; - if (refCount === 0 && !hasErrored && !hasCompleted) { - resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero); - } - }); - dest.subscribe(subscriber); - if (!connection && - refCount > 0) { - connection = new _Subscriber__WEBPACK_IMPORTED_MODULE_2__.SafeSubscriber({ - next: function (value) { return dest.next(value); }, - error: function (err) { - hasErrored = true; - cancelReset(); - resetConnection = handleReset(reset, resetOnError, err); - dest.error(err); - }, - complete: function () { - hasCompleted = true; - cancelReset(); - resetConnection = handleReset(reset, resetOnComplete); - dest.complete(); - }, - }); - (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_3__.innerFrom)(source).subscribe(connection); - } - })(wrapperSource); - }; -} -function handleReset(reset, on) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - if (on === true) { - reset(); - return; - } - if (on === false) { - return; - } - var onSubscriber = new _Subscriber__WEBPACK_IMPORTED_MODULE_2__.SafeSubscriber({ - next: function () { - onSubscriber.unsubscribe(); - reset(); - }, - }); - return (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_3__.innerFrom)(on.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_4__.__read)(args)))).subscribe(onSubscriber); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ subscribeOn: () => (/* binding */ subscribeOn) -/* harmony export */ }); -/* harmony import */ var _util_lift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/lift */ "./node_modules/rxjs/dist/esm5/internal/util/lift.js"); - -function subscribeOn(scheduler, delay) { - if (delay === void 0) { delay = 0; } - return (0,_util_lift__WEBPACK_IMPORTED_MODULE_0__.operate)(function (source, subscriber) { - subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay)); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js": -/*!*************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js ***! - \*************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduleArray: () => (/* binding */ scheduleArray) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); - -function scheduleArray(input, scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - var i = 0; - return scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - } - else { - subscriber.next(input[i++]); - if (!subscriber.closed) { - this.schedule(); - } - } - }); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js": -/*!*********************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js ***! - \*********************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduleAsyncIterable: () => (/* binding */ scheduleAsyncIterable) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/executeSchedule */ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js"); - - -function scheduleAsyncIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); - } - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, function () { - var iterator = input[Symbol.asyncIterator](); - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, function () { - iterator.next().then(function (result) { - if (result.done) { - subscriber.complete(); - } - else { - subscriber.next(result.value); - } - }); - }, 0, true); - }); - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js": -/*!****************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js ***! - \****************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduleIterable: () => (/* binding */ scheduleIterable) -/* harmony export */ }); -/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Observable */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/dist/esm5/internal/symbol/iterator.js"); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/executeSchedule */ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js"); - - - - -function scheduleIterable(input, scheduler) { - return new _Observable__WEBPACK_IMPORTED_MODULE_0__.Observable(function (subscriber) { - var iterator; - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, function () { - iterator = input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_2__.iterator](); - (0,_util_executeSchedule__WEBPACK_IMPORTED_MODULE_1__.executeSchedule)(subscriber, scheduler, function () { - var _a; - var value; - var done; - try { - (_a = iterator.next(), value = _a.value, done = _a.done); - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - } - }, 0, true); - }); - return function () { return (0,_util_isFunction__WEBPACK_IMPORTED_MODULE_3__.isFunction)(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); }; - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js": -/*!******************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduleObservable: () => (/* binding */ scheduleObservable) -/* harmony export */ }); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/observeOn */ "./node_modules/rxjs/dist/esm5/internal/operators/observeOn.js"); -/* harmony import */ var _operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/subscribeOn */ "./node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js"); - - - -function scheduleObservable(input, scheduler) { - return (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(input).pipe((0,_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__.subscribeOn)(scheduler), (0,_operators_observeOn__WEBPACK_IMPORTED_MODULE_2__.observeOn)(scheduler)); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js": -/*!***************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ schedulePromise: () => (/* binding */ schedulePromise) -/* harmony export */ }); -/* harmony import */ var _observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../observable/innerFrom */ "./node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js"); -/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../operators/observeOn */ "./node_modules/rxjs/dist/esm5/internal/operators/observeOn.js"); -/* harmony import */ var _operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/subscribeOn */ "./node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js"); - - - -function schedulePromise(input, scheduler) { - return (0,_observable_innerFrom__WEBPACK_IMPORTED_MODULE_0__.innerFrom)(input).pipe((0,_operators_subscribeOn__WEBPACK_IMPORTED_MODULE_1__.subscribeOn)(scheduler), (0,_operators_observeOn__WEBPACK_IMPORTED_MODULE_2__.observeOn)(scheduler)); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js": -/*!**************************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js ***! - \**************************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduleReadableStreamLike: () => (/* binding */ scheduleReadableStreamLike) -/* harmony export */ }); -/* harmony import */ var _scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./scheduleAsyncIterable */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js"); -/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../util/isReadableStreamLike */ "./node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js"); - - -function scheduleReadableStreamLike(input, scheduler) { - return (0,_scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_0__.scheduleAsyncIterable)((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_1__.readableStreamLikeToAsyncGenerator)(input), scheduler); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js": -/*!*********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js ***! - \*********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ scheduled: () => (/* binding */ scheduled) -/* harmony export */ }); -/* harmony import */ var _scheduleObservable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./scheduleObservable */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js"); -/* harmony import */ var _schedulePromise__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./schedulePromise */ "./node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js"); -/* harmony import */ var _scheduleArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./scheduleArray */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js"); -/* harmony import */ var _scheduleIterable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./scheduleIterable */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js"); -/* harmony import */ var _scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./scheduleAsyncIterable */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js"); -/* harmony import */ var _util_isInteropObservable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../util/isInteropObservable */ "./node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js"); -/* harmony import */ var _util_isPromise__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/isPromise */ "./node_modules/rxjs/dist/esm5/internal/util/isPromise.js"); -/* harmony import */ var _util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/isArrayLike */ "./node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js"); -/* harmony import */ var _util_isIterable__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/isIterable */ "./node_modules/rxjs/dist/esm5/internal/util/isIterable.js"); -/* harmony import */ var _util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/isAsyncIterable */ "./node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js"); -/* harmony import */ var _util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../util/throwUnobservableError */ "./node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js"); -/* harmony import */ var _util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/isReadableStreamLike */ "./node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js"); -/* harmony import */ var _scheduleReadableStreamLike__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./scheduleReadableStreamLike */ "./node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js"); - - - - - - - - - - - - - -function scheduled(input, scheduler) { - if (input != null) { - if ((0,_util_isInteropObservable__WEBPACK_IMPORTED_MODULE_0__.isInteropObservable)(input)) { - return (0,_scheduleObservable__WEBPACK_IMPORTED_MODULE_1__.scheduleObservable)(input, scheduler); - } - if ((0,_util_isArrayLike__WEBPACK_IMPORTED_MODULE_2__.isArrayLike)(input)) { - return (0,_scheduleArray__WEBPACK_IMPORTED_MODULE_3__.scheduleArray)(input, scheduler); - } - if ((0,_util_isPromise__WEBPACK_IMPORTED_MODULE_4__.isPromise)(input)) { - return (0,_schedulePromise__WEBPACK_IMPORTED_MODULE_5__.schedulePromise)(input, scheduler); - } - if ((0,_util_isAsyncIterable__WEBPACK_IMPORTED_MODULE_6__.isAsyncIterable)(input)) { - return (0,_scheduleAsyncIterable__WEBPACK_IMPORTED_MODULE_7__.scheduleAsyncIterable)(input, scheduler); - } - if ((0,_util_isIterable__WEBPACK_IMPORTED_MODULE_8__.isIterable)(input)) { - return (0,_scheduleIterable__WEBPACK_IMPORTED_MODULE_9__.scheduleIterable)(input, scheduler); - } - if ((0,_util_isReadableStreamLike__WEBPACK_IMPORTED_MODULE_10__.isReadableStreamLike)(input)) { - return (0,_scheduleReadableStreamLike__WEBPACK_IMPORTED_MODULE_11__.scheduleReadableStreamLike)(input, scheduler); - } - } - throw (0,_util_throwUnobservableError__WEBPACK_IMPORTED_MODULE_12__.createInvalidObservableTypeError)(input); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/Action.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/Action.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Action: () => (/* binding */ Action) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Subscription */ "./node_modules/rxjs/dist/esm5/internal/Subscription.js"); - - -var Action = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - if (delay === void 0) { delay = 0; } - return this; - }; - return Action; -}(_Subscription__WEBPACK_IMPORTED_MODULE_1__.Subscription)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncAction.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncAction.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AsyncAction: () => (/* binding */ AsyncAction) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Action */ "./node_modules/rxjs/dist/esm5/internal/scheduler/Action.js"); -/* harmony import */ var _intervalProvider__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./intervalProvider */ "./node_modules/rxjs/dist/esm5/internal/scheduler/intervalProvider.js"); -/* harmony import */ var _util_arrRemove__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/arrRemove */ "./node_modules/rxjs/dist/esm5/internal/util/arrRemove.js"); - - - - -var AsyncAction = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - var _a; - if (delay === void 0) { delay = 0; } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) { - if (delay === void 0) { delay = 0; } - return _intervalProvider__WEBPACK_IMPORTED_MODULE_1__.intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) { - if (delay === void 0) { delay = 0; } - if (delay != null && this.delay === delay && this.pending === false) { - return id; - } - if (id != null) { - _intervalProvider__WEBPACK_IMPORTED_MODULE_1__.intervalProvider.clearInterval(id); - } - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, _delay) { - var errored = false; - var errorValue; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = e ? e : new Error('Scheduled action threw falsy error'); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype.unsubscribe = function () { - if (!this.closed) { - var _a = this, id = _a.id, scheduler = _a.scheduler; - var actions = scheduler.actions; - this.work = this.state = this.scheduler = null; - this.pending = false; - (0,_util_arrRemove__WEBPACK_IMPORTED_MODULE_2__.arrRemove)(actions, this); - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - _super.prototype.unsubscribe.call(this); - } - }; - return AsyncAction; -}(_Action__WEBPACK_IMPORTED_MODULE_3__.Action)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncScheduler.js": -/*!**************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncScheduler.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AsyncScheduler: () => (/* binding */ AsyncScheduler) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Scheduler */ "./node_modules/rxjs/dist/esm5/internal/Scheduler.js"); - - -var AsyncScheduler = (function (_super) { - (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__extends)(AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { now = _Scheduler__WEBPACK_IMPORTED_MODULE_1__.Scheduler.now; } - var _this = _super.call(this, SchedulerAction, now) || this; - _this.actions = []; - _this._active = false; - return _this; - } - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this._active) { - actions.push(action); - return; - } - var error; - this._active = true; - do { - if ((error = action.execute(action.state, action.delay))) { - break; - } - } while ((action = actions.shift())); - this._active = false; - if (error) { - while ((action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; -}(_Scheduler__WEBPACK_IMPORTED_MODULE_1__.Scheduler)); - - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/async.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/async.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ async: () => (/* binding */ async), -/* harmony export */ asyncScheduler: () => (/* binding */ asyncScheduler) -/* harmony export */ }); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncAction */ "./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncAction.js"); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AsyncScheduler */ "./node_modules/rxjs/dist/esm5/internal/scheduler/AsyncScheduler.js"); - - -var asyncScheduler = new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_0__.AsyncScheduler(_AsyncAction__WEBPACK_IMPORTED_MODULE_1__.AsyncAction); -var async = asyncScheduler; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/dateTimestampProvider.js": -/*!*********************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/dateTimestampProvider.js ***! - \*********************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ dateTimestampProvider: () => (/* binding */ dateTimestampProvider) -/* harmony export */ }); -var dateTimestampProvider = { - now: function () { - return (dateTimestampProvider.delegate || Date).now(); - }, - delegate: undefined, -}; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/intervalProvider.js": -/*!****************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/intervalProvider.js ***! - \****************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ intervalProvider: () => (/* binding */ intervalProvider) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); - -var intervalProvider = { - setInterval: function (handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = intervalProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) { - return delegate.setInterval.apply(delegate, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([handler, timeout], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(args))); - } - return setInterval.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([handler, timeout], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(args))); - }, - clearInterval: function (handle) { - var delegate = intervalProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle); - }, - delegate: undefined, -}; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js": -/*!***************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ timeoutProvider: () => (/* binding */ timeoutProvider) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); - -var timeoutProvider = { - setTimeout: function (handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = timeoutProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) { - return delegate.setTimeout.apply(delegate, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([handler, timeout], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(args))); - } - return setTimeout.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([handler, timeout], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(args))); - }, - clearTimeout: function (handle) { - var delegate = timeoutProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle); - }, - delegate: undefined, -}; - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/symbol/iterator.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/symbol/iterator.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ getSymbolIterator: () => (/* binding */ getSymbolIterator), -/* harmony export */ iterator: () => (/* binding */ iterator) -/* harmony export */ }); -function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; -} -var iterator = getSymbolIterator(); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/symbol/observable.js": -/*!*******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/symbol/observable.js ***! - \*******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ observable: () => (/* binding */ observable) -/* harmony export */ }); -var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })(); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/EmptyError.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/EmptyError.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EmptyError: () => (/* binding */ EmptyError) -/* harmony export */ }); -/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ "./node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js"); - -var EmptyError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(function (_super) { return function EmptyErrorImpl() { - _super(this); - this.name = 'EmptyError'; - this.message = 'no elements in sequence'; -}; }); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js": -/*!******************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ObjectUnsubscribedError: () => (/* binding */ ObjectUnsubscribedError) -/* harmony export */ }); -/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ "./node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js"); - -var ObjectUnsubscribedError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(function (_super) { - return function ObjectUnsubscribedErrorImpl() { - _super(this); - this.name = 'ObjectUnsubscribedError'; - this.message = 'object unsubscribed'; - }; -}); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js": -/*!**************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ UnsubscriptionError: () => (/* binding */ UnsubscriptionError) -/* harmony export */ }); -/* harmony import */ var _createErrorClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createErrorClass */ "./node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js"); - -var UnsubscriptionError = (0,_createErrorClass__WEBPACK_IMPORTED_MODULE_0__.createErrorClass)(function (_super) { - return function UnsubscriptionErrorImpl(errors) { - _super(this); - this.message = errors - ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') - : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - }; -}); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/args.js": -/*!***********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/args.js ***! - \***********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ popNumber: () => (/* binding */ popNumber), -/* harmony export */ popResultSelector: () => (/* binding */ popResultSelector), -/* harmony export */ popScheduler: () => (/* binding */ popScheduler) -/* harmony export */ }); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); -/* harmony import */ var _isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isScheduler */ "./node_modules/rxjs/dist/esm5/internal/util/isScheduler.js"); - - -function last(arr) { - return arr[arr.length - 1]; -} -function popResultSelector(args) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(last(args)) ? args.pop() : undefined; -} -function popScheduler(args) { - return (0,_isScheduler__WEBPACK_IMPORTED_MODULE_1__.isScheduler)(last(args)) ? args.pop() : undefined; -} -function popNumber(args, defaultValue) { - return typeof last(args) === 'number' ? args.pop() : defaultValue; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/argsArgArrayOrObject.js": -/*!***************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/argsArgArrayOrObject.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ argsArgArrayOrObject: () => (/* binding */ argsArgArrayOrObject) -/* harmony export */ }); -var isArray = Array.isArray; -var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys; -function argsArgArrayOrObject(args) { - if (args.length === 1) { - var first_1 = args[0]; - if (isArray(first_1)) { - return { args: first_1, keys: null }; - } - if (isPOJO(first_1)) { - var keys = getKeys(first_1); - return { - args: keys.map(function (key) { return first_1[key]; }), - keys: keys, - }; - } - } - return { args: args, keys: null }; -} -function isPOJO(obj) { - return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/arrRemove.js": -/*!****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/arrRemove.js ***! - \****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ arrRemove: () => (/* binding */ arrRemove) -/* harmony export */ }); -function arrRemove(arr, item) { - if (arr) { - var index = arr.indexOf(item); - 0 <= index && arr.splice(index, 1); - } -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ createErrorClass: () => (/* binding */ createErrorClass) -/* harmony export */ }); -function createErrorClass(createImpl) { - var _super = function (instance) { - Error.call(instance); - instance.stack = new Error().stack; - }; - var ctorFunc = createImpl(_super); - ctorFunc.prototype = Object.create(Error.prototype); - ctorFunc.prototype.constructor = ctorFunc; - return ctorFunc; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/createObject.js": -/*!*******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/createObject.js ***! - \*******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ createObject: () => (/* binding */ createObject) -/* harmony export */ }); -function createObject(keys, values) { - return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {}); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/errorContext.js": -/*!*******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/errorContext.js ***! - \*******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ captureError: () => (/* binding */ captureError), -/* harmony export */ errorContext: () => (/* binding */ errorContext) -/* harmony export */ }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../config */ "./node_modules/rxjs/dist/esm5/internal/config.js"); - -var context = null; -function errorContext(cb) { - if (_config__WEBPACK_IMPORTED_MODULE_0__.config.useDeprecatedSynchronousErrorHandling) { - var isRoot = !context; - if (isRoot) { - context = { errorThrown: false, error: null }; - } - cb(); - if (isRoot) { - var _a = context, errorThrown = _a.errorThrown, error = _a.error; - context = null; - if (errorThrown) { - throw error; - } - } - } - else { - cb(); - } -} -function captureError(err) { - if (_config__WEBPACK_IMPORTED_MODULE_0__.config.useDeprecatedSynchronousErrorHandling && context) { - context.errorThrown = true; - context.error = err; - } -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js": -/*!**********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js ***! - \**********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ executeSchedule: () => (/* binding */ executeSchedule) -/* harmony export */ }); -function executeSchedule(parentSubscription, scheduler, work, delay, repeat) { - if (delay === void 0) { delay = 0; } - if (repeat === void 0) { repeat = false; } - var scheduleSubscription = scheduler.schedule(function () { - work(); - if (repeat) { - parentSubscription.add(this.schedule(null, delay)); - } - else { - this.unsubscribe(); - } - }, delay); - parentSubscription.add(scheduleSubscription); - if (!repeat) { - return scheduleSubscription; - } -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/identity.js": -/*!***************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/identity.js ***! - \***************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ identity: () => (/* binding */ identity) -/* harmony export */ }); -function identity(x) { - return x; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isArrayLike: () => (/* binding */ isArrayLike) -/* harmony export */ }); -var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js": -/*!**********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js ***! - \**********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isAsyncIterable: () => (/* binding */ isAsyncIterable) -/* harmony export */ }); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - -function isAsyncIterable(obj) { - return Symbol.asyncIterator && (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isDate.js": -/*!*************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isDate.js ***! - \*************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isValidDate: () => (/* binding */ isValidDate) -/* harmony export */ }); -function isValidDate(value) { - return value instanceof Date && !isNaN(value); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isFunction.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isFunction: () => (/* binding */ isFunction) -/* harmony export */ }); -function isFunction(value) { - return typeof value === 'function'; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js": -/*!**************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isInteropObservable: () => (/* binding */ isInteropObservable) -/* harmony export */ }); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../symbol/observable */ "./node_modules/rxjs/dist/esm5/internal/symbol/observable.js"); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - - -function isInteropObservable(input) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(input[_symbol_observable__WEBPACK_IMPORTED_MODULE_1__.observable]); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isIterable.js": -/*!*****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isIterable.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isIterable: () => (/* binding */ isIterable) -/* harmony export */ }); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../symbol/iterator */ "./node_modules/rxjs/dist/esm5/internal/symbol/iterator.js"); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - - -function isIterable(input) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(input === null || input === void 0 ? void 0 : input[_symbol_iterator__WEBPACK_IMPORTED_MODULE_1__.iterator]); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isPromise.js": -/*!****************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isPromise.js ***! - \****************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isPromise: () => (/* binding */ isPromise) -/* harmony export */ }); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - -function isPromise(value) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value === null || value === void 0 ? void 0 : value.then); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js": -/*!***************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isReadableStreamLike: () => (/* binding */ isReadableStreamLike), -/* harmony export */ readableStreamLikeToAsyncGenerator: () => (/* binding */ readableStreamLikeToAsyncGenerator) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - - -function readableStreamLikeToAsyncGenerator(readableStream) { - return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__asyncGenerator)(this, arguments, function readableStreamLikeToAsyncGenerator_1() { - var reader, _a, value, done; - return (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__generator)(this, function (_b) { - switch (_b.label) { - case 0: - reader = readableStream.getReader(); - _b.label = 1; - case 1: - _b.trys.push([1, , 9, 10]); - _b.label = 2; - case 2: - if (false) {} - return [4, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(reader.read())]; - case 3: - _a = _b.sent(), value = _a.value, done = _a.done; - if (!done) return [3, 5]; - return [4, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(void 0)]; - case 4: return [2, _b.sent()]; - case 5: return [4, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__await)(value)]; - case 6: return [4, _b.sent()]; - case 7: - _b.sent(); - return [3, 2]; - case 8: return [3, 10]; - case 9: - reader.releaseLock(); - return [7]; - case 10: return [2]; - } - }); - }); -} -function isReadableStreamLike(obj) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_1__.isFunction)(obj === null || obj === void 0 ? void 0 : obj.getReader); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/isScheduler.js": -/*!******************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/isScheduler.js ***! - \******************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ isScheduler: () => (/* binding */ isScheduler) -/* harmony export */ }); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - -function isScheduler(value) { - return value && (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(value.schedule); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/lift.js": -/*!***********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/lift.js ***! - \***********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ hasLift: () => (/* binding */ hasLift), -/* harmony export */ operate: () => (/* binding */ operate) -/* harmony export */ }); -/* harmony import */ var _isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction */ "./node_modules/rxjs/dist/esm5/internal/util/isFunction.js"); - -function hasLift(source) { - return (0,_isFunction__WEBPACK_IMPORTED_MODULE_0__.isFunction)(source === null || source === void 0 ? void 0 : source.lift); -} -function operate(init) { - return function (source) { - if (hasLift(source)) { - return source.lift(function (liftedSource) { - try { - return init(liftedSource, this); - } - catch (err) { - this.error(err); - } - }); - } - throw new TypeError('Unable to lift unknown Observable type'); - }; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js": -/*!***********************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/mapOneOrManyArgs.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ mapOneOrManyArgs: () => (/* binding */ mapOneOrManyArgs) -/* harmony export */ }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.mjs"); -/* harmony import */ var _operators_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../operators/map */ "./node_modules/rxjs/dist/esm5/internal/operators/map.js"); - - -var isArray = Array.isArray; -function callOrApply(fn, args) { - return isArray(args) ? fn.apply(void 0, (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__spreadArray)([], (0,tslib__WEBPACK_IMPORTED_MODULE_0__.__read)(args))) : fn(args); -} -function mapOneOrManyArgs(fn) { - return (0,_operators_map__WEBPACK_IMPORTED_MODULE_1__.map)(function (args) { return callOrApply(fn, args); }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/noop.js": -/*!***********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/noop.js ***! - \***********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ noop: () => (/* binding */ noop) -/* harmony export */ }); -function noop() { } - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/pipe.js": -/*!***********************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/pipe.js ***! - \***********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ pipe: () => (/* binding */ pipe), -/* harmony export */ pipeFromArray: () => (/* binding */ pipeFromArray) -/* harmony export */ }); -/* harmony import */ var _identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./identity */ "./node_modules/rxjs/dist/esm5/internal/util/identity.js"); - -function pipe() { - var fns = []; - for (var _i = 0; _i < arguments.length; _i++) { - fns[_i] = arguments[_i]; - } - return pipeFromArray(fns); -} -function pipeFromArray(fns) { - if (fns.length === 0) { - return _identity__WEBPACK_IMPORTED_MODULE_0__.identity; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js": -/*!***************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ reportUnhandledError: () => (/* binding */ reportUnhandledError) -/* harmony export */ }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config */ "./node_modules/rxjs/dist/esm5/internal/config.js"); -/* harmony import */ var _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scheduler/timeoutProvider */ "./node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js"); - - -function reportUnhandledError(err) { - _scheduler_timeoutProvider__WEBPACK_IMPORTED_MODULE_0__.timeoutProvider.setTimeout(function () { - var onUnhandledError = _config__WEBPACK_IMPORTED_MODULE_1__.config.onUnhandledError; - if (onUnhandledError) { - onUnhandledError(err); - } - else { - throw err; - } - }); -} - - -/***/ }), - -/***/ "./node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js": -/*!*****************************************************************************!*\ - !*** ./node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js ***! - \*****************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ createInvalidObservableTypeError: () => (/* binding */ createInvalidObservableTypeError) -/* harmony export */ }); -function createInvalidObservableTypeError(input) { - return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable."); -} - - -/***/ }), - -/***/ "./src/dexieCloudNETBase.js": -/*!**********************************!*\ - !*** ./src/dexieCloudNETBase.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ CloudDB: () => (/* binding */ CloudDB), -/* harmony export */ CreateCloud: () => (/* binding */ CreateCloud) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "./node_modules/dexie/import-wrapper.mjs"); -/* harmony import */ var dexie_cloud_addon__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! dexie-cloud-addon */ "./node_modules/dexie-cloud-addon/dist/modern/dexie-cloud-addon.js"); -/* -dexieNET.js - -Copyright(c) 2022 Bernhard Straub - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -'DexieNET' used with permission of David Fahlander -*/ - - -// @ts-ignore -class CloudDB extends dexie__WEBPACK_IMPORTED_MODULE_0__["default"] { - constructor(name) { - super(name, { addons: [dexie_cloud_addon__WEBPACK_IMPORTED_MODULE_1__["default"]] }); - } -} -function CreateCloud(name) { - let db = new CloudDB(name); - return db; -} - - -/***/ }), - -/***/ "./src/dexieCloudNETCloud.js": -/*!***********************************!*\ - !*** ./src/dexieCloudNETCloud.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AcceptInviteMember: () => (/* binding */ AcceptInviteMember), -/* harmony export */ AddOnVersion: () => (/* binding */ AddOnVersion), -/* harmony export */ ClearInviteMember: () => (/* binding */ ClearInviteMember), -/* harmony export */ ConfigureCloud: () => (/* binding */ ConfigureCloud), -/* harmony export */ CurrentUserId: () => (/* binding */ CurrentUserId), -/* harmony export */ GetTiedRealmID: () => (/* binding */ GetTiedRealmID), -/* harmony export */ Logout: () => (/* binding */ Logout), -/* harmony export */ Options: () => (/* binding */ Options), -/* harmony export */ RejectInviteMember: () => (/* binding */ RejectInviteMember), -/* harmony export */ Schema: () => (/* binding */ Schema), -/* harmony export */ Sync: () => (/* binding */ Sync), -/* harmony export */ UserLogin: () => (/* binding */ UserLogin), -/* harmony export */ UsingServiceWorker: () => (/* binding */ UsingServiceWorker) -/* harmony export */ }); -/* harmony import */ var dexie_cloud_addon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie-cloud-addon */ "./node_modules/dexie-cloud-addon/dist/modern/dexie-cloud-addon.js"); -/* -dexieNET.js - -Copyright(c) 2023 Bernhard Straub - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -'DexieNET' used with permission of David Fahlander -*/ - -function ConfigureCloud(db, cloudOptions, dotnetRef) { - try { - if (dotnetRef !== null) { - cloudOptions.fetchTokens = async (tokenParams) => { - return await dotnetRef.invokeMethodAsync('FetchTokens', tokenParams); - }; - } - db.cloud.configure(cloudOptions); - } - catch (err) { - return err.message; - } - return null; -} -function AddOnVersion(db) { - return db.cloud.version; -} -function CurrentUserId(db) { - return db.cloud.currentUserId; -} -function Options(db) { - return db.cloud.options; -} -function Schema(db) { - return db.cloud.schema; -} -function UsingServiceWorker(db) { - return db.cloud.usingServiceWorker; -} -async function UserLogin(db, email, grantType, userId) { - let httpError = undefined; - try { - await db.cloud.login({ email: email, userId: userId, grant_type: grantType }); - } - catch (e) { - httpError = e.message; - } - return httpError; -} -async function Sync(db, sync) { - await db.cloud.sync({ purpose: sync.purpose == 0 ? "push" : "pull", wait: sync.wait }); -} -async function Logout(db, force) { - await db.cloud.logout({ force: force }); -} -function GetTiedRealmID(id) { - return (0,dexie_cloud_addon__WEBPACK_IMPORTED_MODULE_0__.getTiedRealmId)(id); -} -async function AcceptInviteMember(db, id) { - await db.members.update(id, { accepted: new Date(), rejected: undefined }); -} -async function RejectInviteMember(db, id) { - await db.members.update(id, { rejected: new Date(), accepted: undefined }); -} -async function ClearInviteMember(db, id) { - await db.members.update(id, { rejected: undefined, accepted: undefined }); -} - - -/***/ }), - -/***/ "./src/dexieCloudNETObservables.js": -/*!*****************************************!*\ - !*** ./src/dexieCloudNETObservables.js ***! - \*****************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AcceptInvite: () => (/* binding */ AcceptInvite), -/* harmony export */ ClearInvites: () => (/* binding */ ClearInvites), -/* harmony export */ ClearPermissionChecker: () => (/* binding */ ClearPermissionChecker), -/* harmony export */ ClearUserInteraction: () => (/* binding */ ClearUserInteraction), -/* harmony export */ DotNetObservable: () => (/* binding */ DotNetObservable), -/* harmony export */ OnCancelUserInteraction: () => (/* binding */ OnCancelUserInteraction), -/* harmony export */ OnSubmitUserInteraction: () => (/* binding */ OnSubmitUserInteraction), -/* harmony export */ PermissionCheckerAdd: () => (/* binding */ PermissionCheckerAdd), -/* harmony export */ PermissionCheckerDelete: () => (/* binding */ PermissionCheckerDelete), -/* harmony export */ PermissionCheckerUpdate: () => (/* binding */ PermissionCheckerUpdate), -/* harmony export */ RejectInvite: () => (/* binding */ RejectInvite), -/* harmony export */ SubscribeInvites: () => (/* binding */ SubscribeInvites), -/* harmony export */ SubscribePermissionChecker: () => (/* binding */ SubscribePermissionChecker), -/* harmony export */ SubscribePersistedSyncState: () => (/* binding */ SubscribePersistedSyncState), -/* harmony export */ SubscribeRoles: () => (/* binding */ SubscribeRoles), -/* harmony export */ SubscribeSyncComplete: () => (/* binding */ SubscribeSyncComplete), -/* harmony export */ SubscribeSyncState: () => (/* binding */ SubscribeSyncState), -/* harmony export */ SubscribeUserInteraction: () => (/* binding */ SubscribeUserInteraction), -/* harmony export */ SubscribeUserLogin: () => (/* binding */ SubscribeUserLogin), -/* harmony export */ SubscribeWebSocketStatus: () => (/* binding */ SubscribeWebSocketStatus), -/* harmony export */ UnSubscribeJSObservable: () => (/* binding */ UnSubscribeJSObservable) -/* harmony export */ }); -/* -dexieNET.js - -Copyright(c) 2023 Bernhard Straub - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -'DexieNET' used with permission of David Fahlander -*/ -let _uiInteractions = {}; -function UnSubscribeJSObservable(disposable) { - disposable.unsubscribe(); -} -function DotNetObservable(observable, action, dotnetRef, voidObservable = false) { - return observable.subscribe({ - next: (v) => { - if (voidObservable || v != undefined) { - dotnetRef.invokeMethod('OnNext', action(v)); - } - }, - error: (e) => dotnetRef.invokeMethod('OnError', e.message), - complete: () => dotnetRef.invokeMethod('OnCompleted') - }); -} -// sync with DexieNETCloudUI.cs -function SubscribeUserInteraction(db, dotnetRef) { - const action = (res) => { - var type = -1; - const fieldType = (orgType) => { - switch (orgType) { - case 'text': return 0; - case 'email': return 1; - case 'otp': return 2; - case 'password': return 3; - default: throw "SubscribeUserInteraction, undefined field type!"; - } - }; - var field = null; - switch (res.type) { - case 'email': - type = 0; - field = { type: fieldType(res.fields.email.type), label: null, placeholder: res.fields.email.placeholder }; - break; - case 'otp': - type = 1; - field = { type: fieldType(res.fields.otp.type), label: res.fields.otp.label, placeholder: null }; - break; - case 'message-alert': - type = 2; - field = null; - break; - case 'logout-confirmation': - type = 3; - field = null; - break; - default: throw "SubscribeUserInteraction, undefined ui type!"; - } - const alerts = Array(); - res.alerts.forEach(alert => { - var alertType = -1; - switch (alert.type) { - case 'info': - alertType = 0; - break; - case 'warning': - alertType = 1; - break; - case 'error': - alertType = 2; - break; - default: throw "SubscribeUserInteraction, undefined alert type!"; - } - var messageCode = -1; - switch (alert.messageCode) { - case 'OTP_SENT': - messageCode = 0; - break; - case 'INVALID_OTP': - messageCode = 1; - break; - case 'INVALID_EMAIL': - messageCode = 2; - break; - case 'LICENSE_LIMIT_REACHED': - messageCode = 3; - break; - case 'GENERIC_INFO': - messageCode = 4; - break; - case 'GENERIC_WARNING': - messageCode = 5; - break; - case 'GENERIC_ERROR': - messageCode = 6; - break; - case 'LOGOUT_CONFIRMATION': - messageCode = 7; - break; - default: throw "SubscribeUserInteraction, undefined message code!"; - } - alerts.push({ type: alertType, code: messageCode, message: alert.message, params: alert.messageParams }); - }); - const key = Date.now(); - _uiInteractions[key] = res; - return { type: type, title: res.title, alerts: alerts, fields: field, key: key }; - }; - return DotNetObservable(db.cloud.userInteraction, action, dotnetRef); -} -function ClearUserInteraction() { - _uiInteractions = {}; -} -function OnSubmitUserInteraction(key, params) { - const uiInteraction = _uiInteractions[key]; - if (uiInteraction != undefined) { - switch (uiInteraction.type) { - case 'email': - uiInteraction.onSubmit({ email: params['email'] }); - break; - case 'otp': - uiInteraction.onSubmit({ otp: params['otp'] }); - break; - case 'message-alert': - uiInteraction.onSubmit(params); - break; - default: throw "OnSubmitUserInteraction, undefined ui type!"; - } - delete _uiInteractions[key]; - } -} -function OnCancelUserInteraction(key) { - const uiInteraction = _uiInteractions[key]; - if (uiInteraction != undefined) { - uiInteraction.onCancel(); - delete _uiInteractions[key]; - } -} -function SubscribeWebSocketStatus(db, dotnetRef) { - const action = (res) => { - return res; - }; - return DotNetObservable(db.cloud.webSocketStatus, action, dotnetRef); -} -// sync with DexieNETSync.cs -function SubscribeSyncState(db, dotnetRef) { - const action = (res) => { - const status = (orgType) => { - switch (orgType) { - case 'not-started': return 0; - case 'connecting': return 1; - case 'connected': return 2; - case 'disconnected': return 3; - case 'error': return 4; - case 'offline': return 5; - default: throw "SubscribeUserInteraction, undefined field type!"; - } - }; - const phase = (orgType) => { - switch (orgType) { - case 'initial': return 0; - case 'not-in-sync': return 1; - case 'pushing': return 2; - case 'pulling': return 3; - case 'in-sync': return 4; - case 'error': return 5; - case 'offline': return 6; - default: throw "SubscribeUserInteraction, undefined field type!"; - } - }; - return { status: status(res.status), phase: phase(res.phase), progress: res.progress, error: res.error?.message }; - }; - return DotNetObservable(db.cloud.syncState, action, dotnetRef); -} -// sync with DexieNETSync.cs -function SubscribePersistedSyncState(db, dotnetRef) { - const action = (res) => { - return res; - }; - return DotNetObservable(db.cloud.persistedSyncState, action, dotnetRef); -} -function SubscribeSyncComplete(db, dotnetRef) { - const action = (_) => { - return true; - }; - return DotNetObservable(db.cloud.events.syncComplete, action, dotnetRef, true); -} -// sync with DexieNETCloudUser.cs -function SubscribeUserLogin(db, dotnetRef) { - const action = (res) => { - let convert = (o) => Object.fromEntries(Object.keys(o).map(key => [key, o[key].toString()])); - const licenseType = (orgType) => { - switch (orgType) { - case 'demo': return 0; - case 'eval': return 1; - case 'prod': return 2; - case 'client': return 3; - default: throw "SubscribeUserLogin, undefined license type!"; - } - }; - const licenseStatus = (orgType) => { - switch (orgType) { - case 'ok': return 0; - case 'expired': return 1; - case 'deactivated': return 2; - default: throw "SubscribeUserLogin, undefined license status!"; - } - }; - let license = res.license === undefined ? undefined : - { - type: licenseType(res.license.type), status: licenseStatus(res.license.status), - validUntil: res.license.validUntil, evalDaysLeft: res.license.evalDaysLeft - }; - return { - userId: res.userId, name: res.name, email: res.email, claims: convert(res.claims), license: license, - lastlogin: res.lastLogin, accessToken: res.accessToken, accessTokenExpiration: res.accessTokenExpiration, - refreshToken: res.refreshToken, refreshTokenExpiration: res.refreshTokenExpiration, - nonExportablePrivateKey: JSON.stringify(res.nonExportablePrivateKey), publicKey: JSON.stringify(res.publicKey), - isLoggedIn: res.isLoggedIn === undefined ? false : res.isLoggedIn - }; - }; - return DotNetObservable(db.cloud.currentUser, action, dotnetRef); -} -// sync with DexieNETCloudAccesss.cs -let _invites = {}; -function SubscribeInvites(db, dotnetRef) { - const action = (res) => { - ClearInvites(); - res.forEach(i => _invites[i.id] = i); - return res; - }; - return DotNetObservable(db.cloud.invites, action, dotnetRef); -} -function ClearInvites() { - _invites = {}; -} -function AcceptInvite(key) { - const invite = _invites[key]; - if (invite != undefined) { - invite.accept(); - } -} -function RejectInvite(key) { - const invite = _invites[key]; - if (invite != undefined) { - invite.reject(); - } -} -function SubscribeRoles(db, dotnetRef) { - const action = (res) => { - return res; - }; - return DotNetObservable(db.cloud.roles, action, dotnetRef); -} -let _permissionChecker = {}; -function SubscribePermissionChecker(db, dotnetRef, tableName, item) { - const key = Date.now(); - item ??= { owner: undefined, realmId: undefined }; - const action = (res) => { - _permissionChecker[key] = res; - return key; - }; - return DotNetObservable(db.cloud.permissions(item, tableName), action, dotnetRef); -} -function ClearPermissionChecker(key) { - if (_permissionChecker[key] != undefined) { - delete _permissionChecker[key]; - } -} -function PermissionCheckerAdd(key, ...tableNames) { - const pc = _permissionChecker[key]; - if (pc != undefined) { - return pc.add(...tableNames); - } - return false; -} -function PermissionCheckerUpdate(key, ...keys) { - const pc = _permissionChecker[key]; - if (pc != undefined) { - return pc.update(...keys); - } - return false; -} -function PermissionCheckerDelete(key) { - const pc = _permissionChecker[key]; - if (pc != undefined) { - return pc.delete(); - } - return false; -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/node_modules/dexie/dist/dexie.js": -/*!************************************************************!*\ - !*** ../../DexieNET/yarn/node_modules/dexie/dist/dexie.js ***! - \************************************************************/ -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* - * Dexie.js - a minimalistic wrapper for IndexedDB - * =============================================== - * - * By David Fahlander, david.fahlander@gmail.com - * - * Version 4.0.4, Wed Apr 10 2024 - * - * https://dexie.org - * - * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ - */ - -(function (global, factory) { - true ? module.exports = factory() : - 0; -})(this, (function () { 'use strict'; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** */ - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); - } - - var _global = typeof globalThis !== 'undefined' ? globalThis : - typeof self !== 'undefined' ? self : - typeof window !== 'undefined' ? window : - __webpack_require__.g; - - var keys = Object.keys; - var isArray = Array.isArray; - if (typeof Promise !== 'undefined' && !_global.Promise) { - _global.Promise = Promise; - } - function extend(obj, extension) { - if (typeof extension !== 'object') - return obj; - keys(extension).forEach(function (key) { - obj[key] = extension[key]; - }); - return obj; - } - var getProto = Object.getPrototypeOf; - var _hasOwn = {}.hasOwnProperty; - function hasOwn(obj, prop) { - return _hasOwn.call(obj, prop); - } - function props(proto, extension) { - if (typeof extension === 'function') - extension = extension(getProto(proto)); - (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function (key) { - setProp(proto, key, extension[key]); - }); - } - var defineProperty = Object.defineProperty; - function setProp(obj, prop, functionOrGetSet, options) { - defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? - { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : - { value: functionOrGetSet, configurable: true, writable: true }, options)); - } - function derive(Child) { - return { - from: function (Parent) { - Child.prototype = Object.create(Parent.prototype); - setProp(Child.prototype, "constructor", Child); - return { - extend: props.bind(null, Child.prototype) - }; - } - }; - } - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - function getPropertyDescriptor(obj, prop) { - var pd = getOwnPropertyDescriptor(obj, prop); - var proto; - return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); - } - var _slice = [].slice; - function slice(args, start, end) { - return _slice.call(args, start, end); - } - function override(origFunc, overridedFactory) { - return overridedFactory(origFunc); - } - function assert(b) { - if (!b) - throw new Error("Assertion Failed"); - } - function asap$1(fn) { - if (_global.setImmediate) - setImmediate(fn); - else - setTimeout(fn, 0); - } - function arrayToObject(array, extractor) { - return array.reduce(function (result, item, i) { - var nameAndValue = extractor(item, i); - if (nameAndValue) - result[nameAndValue[0]] = nameAndValue[1]; - return result; - }, {}); - } - function getByKeyPath(obj, keyPath) { - if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) - return obj[keyPath]; - if (!keyPath) - return obj; - if (typeof keyPath !== 'string') { - var rv = []; - for (var i = 0, l = keyPath.length; i < l; ++i) { - var val = getByKeyPath(obj, keyPath[i]); - rv.push(val); - } - return rv; - } - var period = keyPath.indexOf('.'); - if (period !== -1) { - var innerObj = obj[keyPath.substr(0, period)]; - return innerObj == null ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); - } - return undefined; - } - function setByKeyPath(obj, keyPath, value) { - if (!obj || keyPath === undefined) - return; - if ('isFrozen' in Object && Object.isFrozen(obj)) - return; - if (typeof keyPath !== 'string' && 'length' in keyPath) { - assert(typeof value !== 'string' && 'length' in value); - for (var i = 0, l = keyPath.length; i < l; ++i) { - setByKeyPath(obj, keyPath[i], value[i]); - } - } - else { - var period = keyPath.indexOf('.'); - if (period !== -1) { - var currentKeyPath = keyPath.substr(0, period); - var remainingKeyPath = keyPath.substr(period + 1); - if (remainingKeyPath === "") - if (value === undefined) { - if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) - obj.splice(currentKeyPath, 1); - else - delete obj[currentKeyPath]; - } - else - obj[currentKeyPath] = value; - else { - var innerObj = obj[currentKeyPath]; - if (!innerObj || !hasOwn(obj, currentKeyPath)) - innerObj = (obj[currentKeyPath] = {}); - setByKeyPath(innerObj, remainingKeyPath, value); - } - } - else { - if (value === undefined) { - if (isArray(obj) && !isNaN(parseInt(keyPath))) - obj.splice(keyPath, 1); - else - delete obj[keyPath]; - } - else - obj[keyPath] = value; - } - } - } - function delByKeyPath(obj, keyPath) { - if (typeof keyPath === 'string') - setByKeyPath(obj, keyPath, undefined); - else if ('length' in keyPath) - [].map.call(keyPath, function (kp) { - setByKeyPath(obj, kp, undefined); - }); - } - function shallowClone(obj) { - var rv = {}; - for (var m in obj) { - if (hasOwn(obj, m)) - rv[m] = obj[m]; - } - return rv; - } - var concat = [].concat; - function flatten(a) { - return concat.apply([], a); - } - var intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" - .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }); - var intrinsicTypes = new Set(intrinsicTypeNames.map(function (t) { return _global[t]; })); - function cloneSimpleObjectTree(o) { - var rv = {}; - for (var k in o) - if (hasOwn(o, k)) { - var v = o[k]; - rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); - } - return rv; - } - function objectIsEmpty(o) { - for (var k in o) - if (hasOwn(o, k)) - return false; - return true; - } - var circularRefs = null; - function deepClone(any) { - circularRefs = new WeakMap(); - var rv = innerDeepClone(any); - circularRefs = null; - return rv; - } - function innerDeepClone(x) { - if (!x || typeof x !== 'object') - return x; - var rv = circularRefs.get(x); - if (rv) - return rv; - if (isArray(x)) { - rv = []; - circularRefs.set(x, rv); - for (var i = 0, l = x.length; i < l; ++i) { - rv.push(innerDeepClone(x[i])); - } - } - else if (intrinsicTypes.has(x.constructor)) { - rv = x; - } - else { - var proto = getProto(x); - rv = proto === Object.prototype ? {} : Object.create(proto); - circularRefs.set(x, rv); - for (var prop in x) { - if (hasOwn(x, prop)) { - rv[prop] = innerDeepClone(x[prop]); - } - } - } - return rv; - } - var toString = {}.toString; - function toStringTag(o) { - return toString.call(o).slice(8, -1); - } - var iteratorSymbol = typeof Symbol !== 'undefined' ? - Symbol.iterator : - '@@iterator'; - var getIteratorOf = typeof iteratorSymbol === "symbol" ? function (x) { - var i; - return x != null && (i = x[iteratorSymbol]) && i.apply(x); - } : function () { return null; }; - function delArrayItem(a, x) { - var i = a.indexOf(x); - if (i >= 0) - a.splice(i, 1); - return i >= 0; - } - var NO_CHAR_ARRAY = {}; - function getArrayOf(arrayLike) { - var i, a, x, it; - if (arguments.length === 1) { - if (isArray(arrayLike)) - return arrayLike.slice(); - if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') - return [arrayLike]; - if ((it = getIteratorOf(arrayLike))) { - a = []; - while ((x = it.next()), !x.done) - a.push(x.value); - return a; - } - if (arrayLike == null) - return [arrayLike]; - i = arrayLike.length; - if (typeof i === 'number') { - a = new Array(i); - while (i--) - a[i] = arrayLike[i]; - return a; - } - return [arrayLike]; - } - i = arguments.length; - a = new Array(i); - while (i--) - a[i] = arguments[i]; - return a; - } - var isAsyncFunction = typeof Symbol !== 'undefined' - ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } - : function () { return false; }; - - var dexieErrorNames = [ - 'Modify', - 'Bulk', - 'OpenFailed', - 'VersionChange', - 'Schema', - 'Upgrade', - 'InvalidTable', - 'MissingAPI', - 'NoSuchDatabase', - 'InvalidArgument', - 'SubTransaction', - 'Unsupported', - 'Internal', - 'DatabaseClosed', - 'PrematureCommit', - 'ForeignAwait' - ]; - var idbDomErrorNames = [ - 'Unknown', - 'Constraint', - 'Data', - 'TransactionInactive', - 'ReadOnly', - 'Version', - 'NotFound', - 'InvalidState', - 'InvalidAccess', - 'Abort', - 'Timeout', - 'QuotaExceeded', - 'Syntax', - 'DataClone' - ]; - var errorList = dexieErrorNames.concat(idbDomErrorNames); - var defaultTexts = { - VersionChanged: "Database version changed by other database connection", - DatabaseClosed: "Database has been closed", - Abort: "Transaction aborted", - TransactionInactive: "Transaction has already completed or failed", - MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" - }; - function DexieError(name, msg) { - this.name = name; - this.message = msg; - } - derive(DexieError).from(Error).extend({ - toString: function () { return this.name + ": " + this.message; } - }); - function getMultiErrorMessage(msg, failures) { - return msg + ". Errors: " + Object.keys(failures) - .map(function (key) { return failures[key].toString(); }) - .filter(function (v, i, s) { return s.indexOf(v) === i; }) - .join('\n'); - } - function ModifyError(msg, failures, successCount, failedKeys) { - this.failures = failures; - this.failedKeys = failedKeys; - this.successCount = successCount; - this.message = getMultiErrorMessage(msg, failures); - } - derive(ModifyError).from(DexieError); - function BulkError(msg, failures) { - this.name = "BulkError"; - this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; }); - this.failuresByPos = failures; - this.message = getMultiErrorMessage(msg, this.failures); - } - derive(BulkError).from(DexieError); - var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); - var BaseException = DexieError; - var exceptions = errorList.reduce(function (obj, name) { - var fullName = name + "Error"; - function DexieError(msgOrInner, inner) { - this.name = fullName; - if (!msgOrInner) { - this.message = defaultTexts[name] || fullName; - this.inner = null; - } - else if (typeof msgOrInner === 'string') { - this.message = "".concat(msgOrInner).concat(!inner ? '' : '\n ' + inner); - this.inner = inner || null; - } - else if (typeof msgOrInner === 'object') { - this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); - this.inner = msgOrInner; - } - } - derive(DexieError).from(BaseException); - obj[name] = DexieError; - return obj; - }, {}); - exceptions.Syntax = SyntaxError; - exceptions.Type = TypeError; - exceptions.Range = RangeError; - var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - function mapError(domError, message) { - if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) - return domError; - var rv = new exceptionMap[domError.name](message || domError.message, domError); - if ("stack" in domError) { - setProp(rv, "stack", { get: function () { - return this.inner.stack; - } }); - } - return rv; - } - var fullNameExceptions = errorList.reduce(function (obj, name) { - if (["Syntax", "Type", "Range"].indexOf(name) === -1) - obj[name + "Error"] = exceptions[name]; - return obj; - }, {}); - fullNameExceptions.ModifyError = ModifyError; - fullNameExceptions.DexieError = DexieError; - fullNameExceptions.BulkError = BulkError; - - function nop() { } - function mirror(val) { return val; } - function pureFunctionChain(f1, f2) { - if (f1 == null || f1 === mirror) - return f2; - return function (val) { - return f2(f1(val)); - }; - } - function callBoth(on1, on2) { - return function () { - on1.apply(this, arguments); - on2.apply(this, arguments); - }; - } - function hookCreatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - var res = f1.apply(this, arguments); - if (res !== undefined) - arguments[0] = res; - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res2 !== undefined ? res2 : res; - }; - } - function hookDeletingChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - f1.apply(this, arguments); - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = this.onerror = null; - f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - }; - } - function hookUpdatingChain(f1, f2) { - if (f1 === nop) - return f2; - return function (modifications) { - var res = f1.apply(this, arguments); - extend(modifications, res); - var onsuccess = this.onsuccess, - onerror = this.onerror; - this.onsuccess = null; - this.onerror = null; - var res2 = f2.apply(this, arguments); - if (onsuccess) - this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; - if (onerror) - this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; - return res === undefined ? - (res2 === undefined ? undefined : res2) : - (extend(res, res2)); - }; - } - function reverseStoppableEventChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - if (f2.apply(this, arguments) === false) - return false; - return f1.apply(this, arguments); - }; - } - function promisableChain(f1, f2) { - if (f1 === nop) - return f2; - return function () { - var res = f1.apply(this, arguments); - if (res && typeof res.then === 'function') { - var thiz = this, i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - return res.then(function () { - return f2.apply(thiz, args); - }); - } - return f2.apply(this, arguments); - }; - } - - var debug = typeof location !== 'undefined' && - /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); - function setDebug(value, filter) { - debug = value; - } - - var INTERNAL = {}; - var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? - [] : - (function () { - var globalP = Promise.resolve(); - if (typeof crypto === 'undefined' || !crypto.subtle) - return [globalP, getProto(globalP), globalP]; - var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); - return [ - nativeP, - getProto(nativeP), - globalP - ]; - })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; - var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; - var patchGlobalPromise = !!resolvedGlobalPromise; - function schedulePhysicalTick() { - queueMicrotask(physicalTick); - } - var asap = function (callback, args) { - microtickQueue.push([callback, args]); - if (needsNewPhysicalTick) { - schedulePhysicalTick(); - needsNewPhysicalTick = false; - } - }; - var isOutsideMicroTick = true, - needsNewPhysicalTick = true, - unhandledErrors = [], - rejectingErrors = [], - rejectionMapper = mirror; - var globalPSD = { - id: 'global', - global: true, - ref: 0, - unhandleds: [], - onunhandled: nop, - pgp: false, - env: {}, - finalize: nop - }; - var PSD = globalPSD; - var microtickQueue = []; - var numScheduledCalls = 0; - var tickFinalizers = []; - function DexiePromise(fn) { - if (typeof this !== 'object') - throw new TypeError('Promises must be constructed via new'); - this._listeners = []; - this._lib = false; - var psd = (this._PSD = PSD); - if (typeof fn !== 'function') { - if (fn !== INTERNAL) - throw new TypeError('Not a function'); - this._state = arguments[1]; - this._value = arguments[2]; - if (this._state === false) - handleRejection(this, this._value); - return; - } - this._state = null; - this._value = null; - ++psd.ref; - executePromiseTask(this, fn); - } - var thenProp = { - get: function () { - var psd = PSD, microTaskId = totalEchoes; - function then(onFulfilled, onRejected) { - var _this = this; - var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); - var cleanup = possibleAwait && !decrementExpectedAwaits(); - var rv = new DexiePromise(function (resolve, reject) { - propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); - }); - if (this._consoleTask) - rv._consoleTask = this._consoleTask; - return rv; - } - then.prototype = INTERNAL; - return then; - }, - set: function (value) { - setProp(this, 'then', value && value.prototype === INTERNAL ? - thenProp : - { - get: function () { - return value; - }, - set: thenProp.set - }); - } - }; - props(DexiePromise.prototype, { - then: thenProp, - _then: function (onFulfilled, onRejected) { - propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); - }, - catch: function (onRejected) { - if (arguments.length === 1) - return this.then(null, onRejected); - var type = arguments[0], handler = arguments[1]; - return typeof type === 'function' ? this.then(null, function (err) { - return err instanceof type ? handler(err) : PromiseReject(err); - }) - : this.then(null, function (err) { - return err && err.name === type ? handler(err) : PromiseReject(err); - }); - }, - finally: function (onFinally) { - return this.then(function (value) { - return DexiePromise.resolve(onFinally()).then(function () { return value; }); - }, function (err) { - return DexiePromise.resolve(onFinally()).then(function () { return PromiseReject(err); }); - }); - }, - timeout: function (ms, msg) { - var _this = this; - return ms < Infinity ? - new DexiePromise(function (resolve, reject) { - var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); - _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); - }) : this; - } - }); - if (typeof Symbol !== 'undefined' && Symbol.toStringTag) - setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); - globalPSD.env = snapShot(); - function Listener(onFulfilled, onRejected, resolve, reject, zone) { - this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; - this.onRejected = typeof onRejected === 'function' ? onRejected : null; - this.resolve = resolve; - this.reject = reject; - this.psd = zone; - } - props(DexiePromise, { - all: function () { - var values = getArrayOf.apply(null, arguments) - .map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - if (values.length === 0) - resolve([]); - var remaining = values.length; - values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { - values[i] = x; - if (!--remaining) - resolve(values); - }, reject); }); - }); - }, - resolve: function (value) { - if (value instanceof DexiePromise) - return value; - if (value && typeof value.then === 'function') - return new DexiePromise(function (resolve, reject) { - value.then(resolve, reject); - }); - var rv = new DexiePromise(INTERNAL, true, value); - return rv; - }, - reject: PromiseReject, - race: function () { - var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); - }); - }, - PSD: { - get: function () { return PSD; }, - set: function (value) { return PSD = value; } - }, - totalEchoes: { get: function () { return totalEchoes; } }, - newPSD: newScope, - usePSD: usePSD, - scheduler: { - get: function () { return asap; }, - set: function (value) { asap = value; } - }, - rejectionMapper: { - get: function () { return rejectionMapper; }, - set: function (value) { rejectionMapper = value; } - }, - follow: function (fn, zoneProps) { - return new DexiePromise(function (resolve, reject) { - return newScope(function (resolve, reject) { - var psd = PSD; - psd.unhandleds = []; - psd.onunhandled = reject; - psd.finalize = callBoth(function () { - var _this = this; - run_at_end_of_this_or_next_physical_tick(function () { - _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); - }); - }, psd.finalize); - fn(); - }, zoneProps, resolve, reject); - }); - } - }); - if (NativePromise) { - if (NativePromise.allSettled) - setProp(DexiePromise, "allSettled", function () { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve) { - if (possiblePromises.length === 0) - resolve([]); - var remaining = possiblePromises.length; - var results = new Array(remaining); - possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) - .then(function () { return --remaining || resolve(results); }); }); - }); - }); - if (NativePromise.any && typeof AggregateError !== 'undefined') - setProp(DexiePromise, "any", function () { - var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); - return new DexiePromise(function (resolve, reject) { - if (possiblePromises.length === 0) - reject(new AggregateError([])); - var remaining = possiblePromises.length; - var failures = new Array(remaining); - possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { - failures[i] = failure; - if (!--remaining) - reject(new AggregateError(failures)); - }); }); - }); - }); - } - function executePromiseTask(promise, fn) { - try { - fn(function (value) { - if (promise._state !== null) - return; - if (value === promise) - throw new TypeError('A promise cannot be resolved with itself.'); - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - if (value && typeof value.then === 'function') { - executePromiseTask(promise, function (resolve, reject) { - value instanceof DexiePromise ? - value._then(resolve, reject) : - value.then(resolve, reject); - }); - } - else { - promise._state = true; - promise._value = value; - propagateAllListeners(promise); - } - if (shouldExecuteTick) - endMicroTickScope(); - }, handleRejection.bind(null, promise)); - } - catch (ex) { - handleRejection(promise, ex); - } - } - function handleRejection(promise, reason) { - rejectingErrors.push(reason); - if (promise._state !== null) - return; - var shouldExecuteTick = promise._lib && beginMicroTickScope(); - reason = rejectionMapper(reason); - promise._state = false; - promise._value = reason; - addPossiblyUnhandledError(promise); - propagateAllListeners(promise); - if (shouldExecuteTick) - endMicroTickScope(); - } - function propagateAllListeners(promise) { - var listeners = promise._listeners; - promise._listeners = []; - for (var i = 0, len = listeners.length; i < len; ++i) { - propagateToListener(promise, listeners[i]); - } - var psd = promise._PSD; - --psd.ref || psd.finalize(); - if (numScheduledCalls === 0) { - ++numScheduledCalls; - asap(function () { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - } - function propagateToListener(promise, listener) { - if (promise._state === null) { - promise._listeners.push(listener); - return; - } - var cb = promise._state ? listener.onFulfilled : listener.onRejected; - if (cb === null) { - return (promise._state ? listener.resolve : listener.reject)(promise._value); - } - ++listener.psd.ref; - ++numScheduledCalls; - asap(callListener, [cb, promise, listener]); - } - function callListener(cb, promise, listener) { - try { - var ret, value = promise._value; - if (!promise._state && rejectingErrors.length) - rejectingErrors = []; - ret = debug && promise._consoleTask ? promise._consoleTask.run(function () { return cb(value); }) : cb(value); - if (!promise._state && rejectingErrors.indexOf(value) === -1) { - markErrorAsHandled(promise); - } - listener.resolve(ret); - } - catch (e) { - listener.reject(e); - } - finally { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - --listener.psd.ref || listener.psd.finalize(); - } - } - function physicalTick() { - usePSD(globalPSD, function () { - beginMicroTickScope() && endMicroTickScope(); - }); - } - function beginMicroTickScope() { - var wasRootExec = isOutsideMicroTick; - isOutsideMicroTick = false; - needsNewPhysicalTick = false; - return wasRootExec; - } - function endMicroTickScope() { - var callbacks, i, l; - do { - while (microtickQueue.length > 0) { - callbacks = microtickQueue; - microtickQueue = []; - l = callbacks.length; - for (i = 0; i < l; ++i) { - var item = callbacks[i]; - item[0].apply(null, item[1]); - } - } - } while (microtickQueue.length > 0); - isOutsideMicroTick = true; - needsNewPhysicalTick = true; - } - function finalizePhysicalTick() { - var unhandledErrs = unhandledErrors; - unhandledErrors = []; - unhandledErrs.forEach(function (p) { - p._PSD.onunhandled.call(null, p._value, p); - }); - var finalizers = tickFinalizers.slice(0); - var i = finalizers.length; - while (i) - finalizers[--i](); - } - function run_at_end_of_this_or_next_physical_tick(fn) { - function finalizer() { - fn(); - tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); - } - tickFinalizers.push(finalizer); - ++numScheduledCalls; - asap(function () { - if (--numScheduledCalls === 0) - finalizePhysicalTick(); - }, []); - } - function addPossiblyUnhandledError(promise) { - if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) - unhandledErrors.push(promise); - } - function markErrorAsHandled(promise) { - var i = unhandledErrors.length; - while (i) - if (unhandledErrors[--i]._value === promise._value) { - unhandledErrors.splice(i, 1); - return; - } - } - function PromiseReject(reason) { - return new DexiePromise(INTERNAL, false, reason); - } - function wrap(fn, errorCatcher) { - var psd = PSD; - return function () { - var wasRootExec = beginMicroTickScope(), outerScope = PSD; - try { - switchToZone(psd, true); - return fn.apply(this, arguments); - } - catch (e) { - errorCatcher && errorCatcher(e); - } - finally { - switchToZone(outerScope, false); - if (wasRootExec) - endMicroTickScope(); - } - }; - } - var task = { awaits: 0, echoes: 0, id: 0 }; - var taskCounter = 0; - var zoneStack = []; - var zoneEchoes = 0; - var totalEchoes = 0; - var zone_id_counter = 0; - function newScope(fn, props, a1, a2) { - var parent = PSD, psd = Object.create(parent); - psd.parent = parent; - psd.ref = 0; - psd.global = false; - psd.id = ++zone_id_counter; - globalPSD.env; - psd.env = patchGlobalPromise ? { - Promise: DexiePromise, - PromiseProp: { value: DexiePromise, configurable: true, writable: true }, - all: DexiePromise.all, - race: DexiePromise.race, - allSettled: DexiePromise.allSettled, - any: DexiePromise.any, - resolve: DexiePromise.resolve, - reject: DexiePromise.reject, - } : {}; - if (props) - extend(psd, props); - ++parent.ref; - psd.finalize = function () { - --this.parent.ref || this.parent.finalize(); - }; - var rv = usePSD(psd, fn, a1, a2); - if (psd.ref === 0) - psd.finalize(); - return rv; - } - function incrementExpectedAwaits() { - if (!task.id) - task.id = ++taskCounter; - ++task.awaits; - task.echoes += ZONE_ECHO_LIMIT; - return task.id; - } - function decrementExpectedAwaits() { - if (!task.awaits) - return false; - if (--task.awaits === 0) - task.id = 0; - task.echoes = task.awaits * ZONE_ECHO_LIMIT; - return true; - } - if (('' + nativePromiseThen).indexOf('[native code]') === -1) { - incrementExpectedAwaits = decrementExpectedAwaits = nop; - } - function onPossibleParallellAsync(possiblePromise) { - if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { - incrementExpectedAwaits(); - return possiblePromise.then(function (x) { - decrementExpectedAwaits(); - return x; - }, function (e) { - decrementExpectedAwaits(); - return rejection(e); - }); - } - return possiblePromise; - } - function zoneEnterEcho(targetZone) { - ++totalEchoes; - if (!task.echoes || --task.echoes === 0) { - task.echoes = task.awaits = task.id = 0; - } - zoneStack.push(PSD); - switchToZone(targetZone, true); - } - function zoneLeaveEcho() { - var zone = zoneStack[zoneStack.length - 1]; - zoneStack.pop(); - switchToZone(zone, false); - } - function switchToZone(targetZone, bEnteringZone) { - var currentZone = PSD; - if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { - queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); - } - if (targetZone === PSD) - return; - PSD = targetZone; - if (currentZone === globalPSD) - globalPSD.env = snapShot(); - if (patchGlobalPromise) { - var GlobalPromise = globalPSD.env.Promise; - var targetEnv = targetZone.env; - if (currentZone.global || targetZone.global) { - Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); - GlobalPromise.all = targetEnv.all; - GlobalPromise.race = targetEnv.race; - GlobalPromise.resolve = targetEnv.resolve; - GlobalPromise.reject = targetEnv.reject; - if (targetEnv.allSettled) - GlobalPromise.allSettled = targetEnv.allSettled; - if (targetEnv.any) - GlobalPromise.any = targetEnv.any; - } - } - } - function snapShot() { - var GlobalPromise = _global.Promise; - return patchGlobalPromise ? { - Promise: GlobalPromise, - PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), - all: GlobalPromise.all, - race: GlobalPromise.race, - allSettled: GlobalPromise.allSettled, - any: GlobalPromise.any, - resolve: GlobalPromise.resolve, - reject: GlobalPromise.reject, - } : {}; - } - function usePSD(psd, fn, a1, a2, a3) { - var outerScope = PSD; - try { - switchToZone(psd, true); - return fn(a1, a2, a3); - } - finally { - switchToZone(outerScope, false); - } - } - function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { - return typeof fn !== 'function' ? fn : function () { - var outerZone = PSD; - if (possibleAwait) - incrementExpectedAwaits(); - switchToZone(zone, true); - try { - return fn.apply(this, arguments); - } - finally { - switchToZone(outerZone, false); - if (cleanup) - queueMicrotask(decrementExpectedAwaits); - } - }; - } - function execInGlobalContext(cb) { - if (Promise === NativePromise && task.echoes === 0) { - if (zoneEchoes === 0) { - cb(); - } - else { - enqueueNativeMicroTask(cb); - } - } - else { - setTimeout(cb, 0); - } - } - var rejection = DexiePromise.reject; - - function tempTransaction(db, mode, storeNames, fn) { - if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { - if (db._state.openComplete) { - return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); - } - if (!db._state.isBeingOpened) { - if (!db._state.autoOpen) - return rejection(new exceptions.DatabaseClosed()); - db.open().catch(nop); - } - return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); - } - else { - var trans = db._createTransaction(mode, storeNames, db._dbSchema); - try { - trans.create(); - db._state.PR1398_maxLoop = 3; - } - catch (ex) { - if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { - console.warn('Dexie: Need to reopen db'); - db.close({ disableAutoOpen: false }); - return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); - } - return rejection(ex); - } - return trans._promise(mode, function (resolve, reject) { - return newScope(function () { - PSD.trans = trans; - return fn(resolve, reject, trans); - }); - }).then(function (result) { - if (mode === 'readwrite') - try { - trans.idbtrans.commit(); - } - catch (_a) { } - return mode === 'readonly' ? result : trans._completion.then(function () { return result; }); - }); - } - } - - var DEXIE_VERSION = '4.0.4'; - var maxString = String.fromCharCode(65535); - var minKey = -Infinity; - var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; - var STRING_EXPECTED = "String expected."; - var connections = []; - var DBNAMES_DB = '__dbnames'; - var READONLY = 'readonly'; - var READWRITE = 'readwrite'; - - function combine(filter1, filter2) { - return filter1 ? - filter2 ? - function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : - filter1 : - filter2; - } - - var AnyRange = { - type: 3 , - lower: -Infinity, - lowerOpen: false, - upper: [[]], - upperOpen: false - }; - - function workaroundForUndefinedPrimKey(keyPath) { - return typeof keyPath === "string" && !/\./.test(keyPath) - ? function (obj) { - if (obj[keyPath] === undefined && (keyPath in obj)) { - obj = deepClone(obj); - delete obj[keyPath]; - } - return obj; - } - : function (obj) { return obj; }; - } - - function Entity() { - throw exceptions.Type(); - } - - function cmp(a, b) { - try { - var ta = type(a); - var tb = type(b); - if (ta !== tb) { - if (ta === 'Array') - return 1; - if (tb === 'Array') - return -1; - if (ta === 'binary') - return 1; - if (tb === 'binary') - return -1; - if (ta === 'string') - return 1; - if (tb === 'string') - return -1; - if (ta === 'Date') - return 1; - if (tb !== 'Date') - return NaN; - return -1; - } - switch (ta) { - case 'number': - case 'Date': - case 'string': - return a > b ? 1 : a < b ? -1 : 0; - case 'binary': { - return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); - } - case 'Array': - return compareArrays(a, b); - } - } - catch (_a) { } - return NaN; - } - function compareArrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - var res = cmp(a[i], b[i]); - if (res !== 0) - return res; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function compareUint8Arrays(a, b) { - var al = a.length; - var bl = b.length; - var l = al < bl ? al : bl; - for (var i = 0; i < l; ++i) { - if (a[i] !== b[i]) - return a[i] < b[i] ? -1 : 1; - } - return al === bl ? 0 : al < bl ? -1 : 1; - } - function type(x) { - var t = typeof x; - if (t !== 'object') - return t; - if (ArrayBuffer.isView(x)) - return 'binary'; - var tsTag = toStringTag(x); - return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; - } - function getUint8Array(a) { - if (a instanceof Uint8Array) - return a; - if (ArrayBuffer.isView(a)) - return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); - return new Uint8Array(a); - } - - var Table = (function () { - function Table() { - } - Table.prototype._trans = function (mode, fn, writeLocked) { - var trans = this._tx || PSD.trans; - var tableName = this.name; - var task = debug && typeof console !== 'undefined' && console.createTask && console.createTask("Dexie: ".concat(mode === 'readonly' ? 'read' : 'write', " ").concat(this.name)); - function checkTableInTransaction(resolve, reject, trans) { - if (!trans.schema[tableName]) - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - return fn(trans.idbtrans, trans); - } - var wasRootExec = beginMicroTickScope(); - try { - var p = trans && trans.db._novip === this.db._novip ? - trans === PSD.trans ? - trans._promise(mode, checkTableInTransaction, writeLocked) : - newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : - tempTransaction(this.db, mode, [this.name], checkTableInTransaction); - if (task) { - p._consoleTask = task; - p = p.catch(function (err) { - console.trace(err); - return rejection(err); - }); - } - return p; - } - finally { - if (wasRootExec) - endMicroTickScope(); - } - }; - Table.prototype.get = function (keyOrCrit, cb) { - var _this = this; - if (keyOrCrit && keyOrCrit.constructor === Object) - return this.where(keyOrCrit).first(cb); - if (keyOrCrit == null) - return rejection(new exceptions.Type("Invalid argument to Table.get()")); - return this._trans('readonly', function (trans) { - return _this.core.get({ trans: trans, key: keyOrCrit }) - .then(function (res) { return _this.hook.reading.fire(res); }); - }).then(cb); - }; - Table.prototype.where = function (indexOrCrit) { - if (typeof indexOrCrit === 'string') - return new this.db.WhereClause(this, indexOrCrit); - if (isArray(indexOrCrit)) - return new this.db.WhereClause(this, "[".concat(indexOrCrit.join('+'), "]")); - var keyPaths = keys(indexOrCrit); - if (keyPaths.length === 1) - return this - .where(keyPaths[0]) - .equals(indexOrCrit[keyPaths[0]]); - var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { - if (ix.compound && - keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { - for (var i = 0; i < keyPaths.length; ++i) { - if (keyPaths.indexOf(ix.keyPath[i]) === -1) - return false; - } - return true; - } - return false; - }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; - if (compoundIndex && this.db._maxKey !== maxString) { - var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); - return this - .where(keyPathsInValidOrder) - .equals(keyPathsInValidOrder.map(function (kp) { return indexOrCrit[kp]; })); - } - if (!compoundIndex && debug) - console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit from a ") + - "compound index [".concat(keyPaths.join('+'), "]")); - var idxByName = this.schema.idxByName; - var idb = this.db._deps.indexedDB; - function equals(a, b) { - return idb.cmp(a, b) === 0; - } - var _a = keyPaths.reduce(function (_a, keyPath) { - var prevIndex = _a[0], prevFilterFn = _a[1]; - var index = idxByName[keyPath]; - var value = indexOrCrit[keyPath]; - return [ - prevIndex || index, - prevIndex || !index ? - combine(prevFilterFn, index && index.multi ? - function (x) { - var prop = getByKeyPath(x, keyPath); - return isArray(prop) && prop.some(function (item) { return equals(value, item); }); - } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) - : prevFilterFn - ]; - }, [null, null]), idx = _a[0], filterFunction = _a[1]; - return idx ? - this.where(idx.name).equals(indexOrCrit[idx.keyPath]) - .filter(filterFunction) : - compoundIndex ? - this.filter(filterFunction) : - this.where(keyPaths).equals(''); - }; - Table.prototype.filter = function (filterFunction) { - return this.toCollection().and(filterFunction); - }; - Table.prototype.count = function (thenShortcut) { - return this.toCollection().count(thenShortcut); - }; - Table.prototype.offset = function (offset) { - return this.toCollection().offset(offset); - }; - Table.prototype.limit = function (numRows) { - return this.toCollection().limit(numRows); - }; - Table.prototype.each = function (callback) { - return this.toCollection().each(callback); - }; - Table.prototype.toArray = function (thenShortcut) { - return this.toCollection().toArray(thenShortcut); - }; - Table.prototype.toCollection = function () { - return new this.db.Collection(new this.db.WhereClause(this)); - }; - Table.prototype.orderBy = function (index) { - return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? - "[".concat(index.join('+'), "]") : - index)); - }; - Table.prototype.reverse = function () { - return this.toCollection().reverse(); - }; - Table.prototype.mapToClass = function (constructor) { - var _a = this, db = _a.db, tableName = _a.name; - this.schema.mappedClass = constructor; - if (constructor.prototype instanceof Entity) { - constructor = (function (_super) { - __extends(class_1, _super); - function class_1() { - return _super !== null && _super.apply(this, arguments) || this; - } - Object.defineProperty(class_1.prototype, "db", { - get: function () { return db; }, - enumerable: false, - configurable: true - }); - class_1.prototype.table = function () { return tableName; }; - return class_1; - }(constructor)); - } - var inheritedProps = new Set(); - for (var proto = constructor.prototype; proto; proto = getProto(proto)) { - Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); }); - } - var readHook = function (obj) { - if (!obj) - return obj; - var res = Object.create(constructor.prototype); - for (var m in obj) - if (!inheritedProps.has(m)) - try { - res[m] = obj[m]; - } - catch (_) { } - return res; - }; - if (this.schema.readHook) { - this.hook.reading.unsubscribe(this.schema.readHook); - } - this.schema.readHook = readHook; - this.hook("reading", readHook); - return constructor; - }; - Table.prototype.defineClass = function () { - function Class(content) { - extend(this, content); - } - return this.mapToClass(Class); - }; - Table.prototype.add = function (obj, key) { - var _this = this; - var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans('readwrite', function (trans) { - return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); - }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) - .then(function (lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } - catch (_) { } - } - return lastResult; - }); - }; - Table.prototype.update = function (keyOrObject, modifications) { - if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { - var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); - if (key === undefined) - return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); - return this.where(":id").equals(key).modify(modifications); - } - else { - return this.where(":id").equals(keyOrObject).modify(modifications); - } - }; - Table.prototype.put = function (obj, key) { - var _this = this; - var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - var objToAdd = obj; - if (keyPath && auto) { - objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); - } - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) - .then(function (lastResult) { - if (keyPath) { - try { - setByKeyPath(obj, keyPath, lastResult); - } - catch (_) { } - } - return lastResult; - }); - }; - Table.prototype.delete = function (key) { - var _this = this; - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); - }; - Table.prototype.clear = function () { - var _this = this; - return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) - .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); - }; - Table.prototype.bulkGet = function (keys) { - var _this = this; - return this._trans('readonly', function (trans) { - return _this.core.getMany({ - keys: keys, - trans: trans - }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); - }); - }; - Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { - var _this = this; - var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; - options = options || (keys ? undefined : keysOrOptions); - var wantResults = options ? options.allKeys : undefined; - return this._trans('readwrite', function (trans) { - var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - if (keyPath && keys) - throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); - if (keys && keys.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToAdd = keyPath && auto ? - objects.map(workaroundForUndefinedPrimKey(keyPath)) : - objects; - return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, wantResults: wantResults }) - .then(function (_a) { - var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table.prototype.bulkPut = function (objects, keysOrOptions, options) { - var _this = this; - var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; - options = options || (keys ? undefined : keysOrOptions); - var wantResults = options ? options.allKeys : undefined; - return this._trans('readwrite', function (trans) { - var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; - if (keyPath && keys) - throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); - if (keys && keys.length !== objects.length) - throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); - var numObjects = objects.length; - var objectsToPut = keyPath && auto ? - objects.map(workaroundForUndefinedPrimKey(keyPath)) : - objects; - return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, wantResults: wantResults }) - .then(function (_a) { - var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; - var result = wantResults ? results : lastResult; - if (numFailures === 0) - return result; - throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); - }); - }); - }; - Table.prototype.bulkUpdate = function (keysAndChanges) { - var _this = this; - var coreTable = this.core; - var keys = keysAndChanges.map(function (entry) { return entry.key; }); - var changeSpecs = keysAndChanges.map(function (entry) { return entry.changes; }); - var offsetMap = []; - return this._trans('readwrite', function (trans) { - return coreTable.getMany({ trans: trans, keys: keys, cache: 'clone' }).then(function (objs) { - var resultKeys = []; - var resultObjs = []; - keysAndChanges.forEach(function (_a, idx) { - var key = _a.key, changes = _a.changes; - var obj = objs[idx]; - if (obj) { - for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { - var keyPath = _b[_i]; - var value = changes[keyPath]; - if (keyPath === _this.schema.primKey.keyPath) { - if (cmp(value, key) !== 0) { - throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); - } - } - else { - setByKeyPath(obj, keyPath, value); - } - } - offsetMap.push(idx); - resultKeys.push(key); - resultObjs.push(obj); - } - }); - var numEntries = resultKeys.length; - return coreTable - .mutate({ - trans: trans, - type: 'put', - keys: resultKeys, - values: resultObjs, - updates: { - keys: keys, - changeSpecs: changeSpecs - } - }) - .then(function (_a) { - var numFailures = _a.numFailures, failures = _a.failures; - if (numFailures === 0) - return numEntries; - for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { - var offset = _b[_i]; - var mappedOffset = offsetMap[Number(offset)]; - if (mappedOffset != null) { - var failure = failures[offset]; - delete failures[offset]; - failures[mappedOffset] = failure; - } - } - throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); - }); - }); - }); - }; - Table.prototype.bulkDelete = function (keys) { - var _this = this; - var numKeys = keys.length; - return this._trans('readwrite', function (trans) { - return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); - }).then(function (_a) { - var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; - if (numFailures === 0) - return lastResult; - throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); - }); - }; - return Table; - }()); - - function Events(ctx) { - var evs = {}; - var rv = function (eventName, subscriber) { - if (subscriber) { - var i = arguments.length, args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - evs[eventName].subscribe.apply(null, args); - return ctx; - } - else if (typeof (eventName) === 'string') { - return evs[eventName]; - } - }; - rv.addEventType = add; - for (var i = 1, l = arguments.length; i < l; ++i) { - add(arguments[i]); - } - return rv; - function add(eventName, chainFunction, defaultFunction) { - if (typeof eventName === 'object') - return addConfiguredEvents(eventName); - if (!chainFunction) - chainFunction = reverseStoppableEventChain; - if (!defaultFunction) - defaultFunction = nop; - var context = { - subscribers: [], - fire: defaultFunction, - subscribe: function (cb) { - if (context.subscribers.indexOf(cb) === -1) { - context.subscribers.push(cb); - context.fire = chainFunction(context.fire, cb); - } - }, - unsubscribe: function (cb) { - context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); - context.fire = context.subscribers.reduce(chainFunction, defaultFunction); - } - }; - evs[eventName] = rv[eventName] = context; - return context; - } - function addConfiguredEvents(cfg) { - keys(cfg).forEach(function (eventName) { - var args = cfg[eventName]; - if (isArray(args)) { - add(eventName, cfg[eventName][0], cfg[eventName][1]); - } - else if (args === 'asap') { - var context = add(eventName, mirror, function fire() { - var i = arguments.length, args = new Array(i); - while (i--) - args[i] = arguments[i]; - context.subscribers.forEach(function (fn) { - asap$1(function fireEvent() { - fn.apply(null, args); - }); - }); - }); - } - else - throw new exceptions.InvalidArgument("Invalid event config"); - }); - } - } - - function makeClassConstructor(prototype, constructor) { - derive(constructor).from({ prototype: prototype }); - return constructor; - } - - function createTableConstructor(db) { - return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) { - this.db = db; - this._tx = trans; - this.name = name; - this.schema = tableSchema; - this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { - "creating": [hookCreatingChain, nop], - "reading": [pureFunctionChain, mirror], - "updating": [hookUpdatingChain, nop], - "deleting": [hookDeletingChain, nop] - }); - }); - } - - function isPlainKeyRange(ctx, ignoreLimitFilter) { - return !(ctx.filter || ctx.algorithm || ctx.or) && - (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); - } - function addFilter(ctx, fn) { - ctx.filter = combine(ctx.filter, fn); - } - function addReplayFilter(ctx, factory, isLimitFilter) { - var curr = ctx.replayFilter; - ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; - ctx.justLimit = isLimitFilter && !curr; - } - function addMatchFilter(ctx, fn) { - ctx.isMatch = combine(ctx.isMatch, fn); - } - function getIndexOrStore(ctx, coreSchema) { - if (ctx.isPrimKey) - return coreSchema.primaryKey; - var index = coreSchema.getIndexByKeyPath(ctx.index); - if (!index) - throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); - return index; - } - function openCursor(ctx, coreTable, trans) { - var index = getIndexOrStore(ctx, coreTable.schema); - return coreTable.openCursor({ - trans: trans, - values: !ctx.keysOnly, - reverse: ctx.dir === 'prev', - unique: !!ctx.unique, - query: { - index: index, - range: ctx.range - } - }); - } - function iter(ctx, fn, coreTrans, coreTable) { - var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; - if (!ctx.or) { - return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); - } - else { - var set_1 = {}; - var union = function (item, cursor, advance) { - if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { - var primaryKey = cursor.primaryKey; - var key = '' + primaryKey; - if (key === '[object ArrayBuffer]') - key = '' + new Uint8Array(primaryKey); - if (!hasOwn(set_1, key)) { - set_1[key] = true; - fn(item, cursor, advance); - } - } - }; - return Promise.all([ - ctx.or._iterate(union, coreTrans), - iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) - ]); - } - } - function iterate(cursorPromise, filter, fn, valueMapper) { - var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; - var wrappedFn = wrap(mappedFn); - return cursorPromise.then(function (cursor) { - if (cursor) { - return cursor.start(function () { - var c = function () { return cursor.continue(); }; - if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) - wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); - c(); - }); - } - }); - } - - var PropModSymbol = Symbol(); - var PropModification = (function () { - function PropModification(spec) { - Object.assign(this, spec); - } - PropModification.prototype.execute = function (value) { - var _a; - var prefixToReplace = (_a = this.replacePrefix) === null || _a === void 0 ? void 0 : _a[0]; - if (prefixToReplace && typeof value === 'string' && value.startsWith(prefixToReplace)) { - return this.replacePrefix[1] + value.substring(prefixToReplace.length); - } - return value; - }; - return PropModification; - }()); - - var Collection = (function () { - function Collection() { - } - Collection.prototype._read = function (fn, cb) { - var ctx = this._ctx; - return ctx.error ? - ctx.table._trans(null, rejection.bind(null, ctx.error)) : - ctx.table._trans('readonly', fn).then(cb); - }; - Collection.prototype._write = function (fn) { - var ctx = this._ctx; - return ctx.error ? - ctx.table._trans(null, rejection.bind(null, ctx.error)) : - ctx.table._trans('readwrite', fn, "locked"); - }; - Collection.prototype._addAlgorithm = function (fn) { - var ctx = this._ctx; - ctx.algorithm = combine(ctx.algorithm, fn); - }; - Collection.prototype._iterate = function (fn, coreTrans) { - return iter(this._ctx, fn, coreTrans, this._ctx.table.core); - }; - Collection.prototype.clone = function (props) { - var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); - if (props) - extend(ctx, props); - rv._ctx = ctx; - return rv; - }; - Collection.prototype.raw = function () { - this._ctx.valueMapper = null; - return this; - }; - Collection.prototype.each = function (fn) { - var ctx = this._ctx; - return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); - }; - Collection.prototype.count = function (cb) { - var _this = this; - return this._read(function (trans) { - var ctx = _this._ctx; - var coreTable = ctx.table.core; - if (isPlainKeyRange(ctx, true)) { - return coreTable.count({ - trans: trans, - query: { - index: getIndexOrStore(ctx, coreTable.schema), - range: ctx.range - } - }).then(function (count) { return Math.min(count, ctx.limit); }); - } - else { - var count = 0; - return iter(ctx, function () { ++count; return false; }, trans, coreTable) - .then(function () { return count; }); - } - }).then(cb); - }; - Collection.prototype.sortBy = function (keyPath, cb) { - var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; - function getval(obj, i) { - if (i) - return getval(obj[parts[i]], i - 1); - return obj[lastPart]; - } - var order = this._ctx.dir === "next" ? 1 : -1; - function sorter(a, b) { - var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); - return aVal < bVal ? -order : aVal > bVal ? order : 0; - } - return this.toArray(function (a) { - return a.sort(sorter); - }).then(cb); - }; - Collection.prototype.toArray = function (cb) { - var _this = this; - return this._read(function (trans) { - var ctx = _this._ctx; - if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { - var valueMapper_1 = ctx.valueMapper; - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans: trans, - limit: ctx.limit, - values: true, - query: { - index: index, - range: ctx.range - } - }).then(function (_a) { - var result = _a.result; - return valueMapper_1 ? result.map(valueMapper_1) : result; - }); - } - else { - var a_1 = []; - return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); - } - }, cb); - }; - Collection.prototype.offset = function (offset) { - var ctx = this._ctx; - if (offset <= 0) - return this; - ctx.offset += offset; - if (isPlainKeyRange(ctx)) { - addReplayFilter(ctx, function () { - var offsetLeft = offset; - return function (cursor, advance) { - if (offsetLeft === 0) - return true; - if (offsetLeft === 1) { - --offsetLeft; - return false; - } - advance(function () { - cursor.advance(offsetLeft); - offsetLeft = 0; - }); - return false; - }; - }); - } - else { - addReplayFilter(ctx, function () { - var offsetLeft = offset; - return function () { return (--offsetLeft < 0); }; - }); - } - return this; - }; - Collection.prototype.limit = function (numRows) { - this._ctx.limit = Math.min(this._ctx.limit, numRows); - addReplayFilter(this._ctx, function () { - var rowsLeft = numRows; - return function (cursor, advance, resolve) { - if (--rowsLeft <= 0) - advance(resolve); - return rowsLeft >= 0; - }; - }, true); - return this; - }; - Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { - addFilter(this._ctx, function (cursor, advance, resolve) { - if (filterFunction(cursor.value)) { - advance(resolve); - return bIncludeStopEntry; - } - else { - return true; - } - }); - return this; - }; - Collection.prototype.first = function (cb) { - return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); - }; - Collection.prototype.last = function (cb) { - return this.reverse().first(cb); - }; - Collection.prototype.filter = function (filterFunction) { - addFilter(this._ctx, function (cursor) { - return filterFunction(cursor.value); - }); - addMatchFilter(this._ctx, filterFunction); - return this; - }; - Collection.prototype.and = function (filter) { - return this.filter(filter); - }; - Collection.prototype.or = function (indexName) { - return new this.db.WhereClause(this._ctx.table, indexName, this); - }; - Collection.prototype.reverse = function () { - this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); - if (this._ondirectionchange) - this._ondirectionchange(this._ctx.dir); - return this; - }; - Collection.prototype.desc = function () { - return this.reverse(); - }; - Collection.prototype.eachKey = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function (val, cursor) { cb(cursor.key, cursor); }); - }; - Collection.prototype.eachUniqueKey = function (cb) { - this._ctx.unique = "unique"; - return this.eachKey(cb); - }; - Collection.prototype.eachPrimaryKey = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); - }; - Collection.prototype.keys = function (cb) { - var ctx = this._ctx; - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function (item, cursor) { - a.push(cursor.key); - }).then(function () { - return a; - }).then(cb); - }; - Collection.prototype.primaryKeys = function (cb) { - var ctx = this._ctx; - if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { - return this._read(function (trans) { - var index = getIndexOrStore(ctx, ctx.table.core.schema); - return ctx.table.core.query({ - trans: trans, - values: false, - limit: ctx.limit, - query: { - index: index, - range: ctx.range - } - }); - }).then(function (_a) { - var result = _a.result; - return result; - }).then(cb); - } - ctx.keysOnly = !ctx.isMatch; - var a = []; - return this.each(function (item, cursor) { - a.push(cursor.primaryKey); - }).then(function () { - return a; - }).then(cb); - }; - Collection.prototype.uniqueKeys = function (cb) { - this._ctx.unique = "unique"; - return this.keys(cb); - }; - Collection.prototype.firstKey = function (cb) { - return this.limit(1).keys(function (a) { return a[0]; }).then(cb); - }; - Collection.prototype.lastKey = function (cb) { - return this.reverse().firstKey(cb); - }; - Collection.prototype.distinct = function () { - var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; - if (!idx || !idx.multi) - return this; - var set = {}; - addFilter(this._ctx, function (cursor) { - var strKey = cursor.primaryKey.toString(); - var found = hasOwn(set, strKey); - set[strKey] = true; - return !found; - }); - return this; - }; - Collection.prototype.modify = function (changes) { - var _this = this; - var ctx = this._ctx; - return this._write(function (trans) { - var modifyer; - if (typeof changes === 'function') { - modifyer = changes; - } - else { - var keyPaths = keys(changes); - var numKeys = keyPaths.length; - modifyer = function (item) { - var anythingModified = false; - for (var i = 0; i < numKeys; ++i) { - var keyPath = keyPaths[i]; - var val = changes[keyPath]; - var origVal = getByKeyPath(item, keyPath); - if (val instanceof PropModification) { - setByKeyPath(item, keyPath, val.execute(origVal)); - anythingModified = true; - } - else if (origVal !== val) { - setByKeyPath(item, keyPath, val); - anythingModified = true; - } - } - return anythingModified; - }; - } - var coreTable = ctx.table.core; - var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; - var limit = _this.db._options.modifyChunkSize || 200; - var totalFailures = []; - var successCount = 0; - var failedKeys = []; - var applyMutateResult = function (expectedCount, res) { - var failures = res.failures, numFailures = res.numFailures; - successCount += expectedCount - numFailures; - for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { - var pos = _a[_i]; - totalFailures.push(failures[pos]); - } - }; - return _this.clone().primaryKeys().then(function (keys) { - var nextChunk = function (offset) { - var count = Math.min(limit, keys.length - offset); - return coreTable.getMany({ - trans: trans, - keys: keys.slice(offset, offset + count), - cache: "immutable" - }).then(function (values) { - var addValues = []; - var putValues = []; - var putKeys = outbound ? [] : null; - var deleteKeys = []; - for (var i = 0; i < count; ++i) { - var origValue = values[i]; - var ctx_1 = { - value: deepClone(origValue), - primKey: keys[offset + i] - }; - if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { - if (ctx_1.value == null) { - deleteKeys.push(keys[offset + i]); - } - else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { - deleteKeys.push(keys[offset + i]); - addValues.push(ctx_1.value); - } - else { - putValues.push(ctx_1.value); - if (outbound) - putKeys.push(keys[offset + i]); - } - } - } - var criteria = isPlainKeyRange(ctx) && - ctx.limit === Infinity && - (typeof changes !== 'function' || changes === deleteCallback) && { - index: ctx.index, - range: ctx.range - }; - return Promise.resolve(addValues.length > 0 && - coreTable.mutate({ trans: trans, type: 'add', values: addValues }) - .then(function (res) { - for (var pos in res.failures) { - deleteKeys.splice(parseInt(pos), 1); - } - applyMutateResult(addValues.length, res); - })).then(function () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && - coreTable.mutate({ - trans: trans, - type: 'put', - keys: putKeys, - values: putValues, - criteria: criteria, - changeSpec: typeof changes !== 'function' - && changes - }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && - coreTable.mutate({ - trans: trans, - type: 'delete', - keys: deleteKeys, - criteria: criteria - }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { - return keys.length > offset + count && nextChunk(offset + limit); - }); - }); - }; - return nextChunk(0).then(function () { - if (totalFailures.length > 0) - throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); - return keys.length; - }); - }); - }); - }; - Collection.prototype.delete = function () { - var ctx = this._ctx, range = ctx.range; - if (isPlainKeyRange(ctx) && - (ctx.isPrimKey || range.type === 3 )) - { - return this._write(function (trans) { - var primaryKey = ctx.table.core.schema.primaryKey; - var coreRange = range; - return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { - return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) - .then(function (_a) { - var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures; - if (numFailures) - throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); - return count - numFailures; - }); - }); - }); - } - return this.modify(deleteCallback); - }; - return Collection; - }()); - var deleteCallback = function (value, ctx) { return ctx.value = null; }; - - function createCollectionConstructor(db) { - return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { - this.db = db; - var keyRange = AnyRange, error = null; - if (keyRangeGenerator) - try { - keyRange = keyRangeGenerator(); - } - catch (ex) { - error = ex; - } - var whereCtx = whereClause._ctx; - var table = whereCtx.table; - var readingHook = table.hook.reading.fire; - this._ctx = { - table: table, - index: whereCtx.index, - isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), - range: keyRange, - keysOnly: false, - dir: "next", - unique: "", - algorithm: null, - filter: null, - replayFilter: null, - justLimit: true, - isMatch: null, - offset: 0, - limit: Infinity, - error: error, - or: whereCtx.or, - valueMapper: readingHook !== mirror ? readingHook : null - }; - }); - } - - function simpleCompare(a, b) { - return a < b ? -1 : a === b ? 0 : 1; - } - function simpleCompareReverse(a, b) { - return a > b ? -1 : a === b ? 0 : 1; - } - - function fail(collectionOrWhereClause, err, T) { - var collection = collectionOrWhereClause instanceof WhereClause ? - new collectionOrWhereClause.Collection(collectionOrWhereClause) : - collectionOrWhereClause; - collection._ctx.error = T ? new T(err) : new TypeError(err); - return collection; - } - function emptyCollection(whereClause) { - return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).limit(0); - } - function upperFactory(dir) { - return dir === "next" ? - function (s) { return s.toUpperCase(); } : - function (s) { return s.toLowerCase(); }; - } - function lowerFactory(dir) { - return dir === "next" ? - function (s) { return s.toLowerCase(); } : - function (s) { return s.toUpperCase(); }; - } - function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { - var length = Math.min(key.length, lowerNeedle.length); - var llp = -1; - for (var i = 0; i < length; ++i) { - var lwrKeyChar = lowerKey[i]; - if (lwrKeyChar !== lowerNeedle[i]) { - if (cmp(key[i], upperNeedle[i]) < 0) - return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); - if (cmp(key[i], lowerNeedle[i]) < 0) - return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); - if (llp >= 0) - return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); - return null; - } - if (cmp(key[i], lwrKeyChar) < 0) - llp = i; - } - if (length < lowerNeedle.length && dir === "next") - return key + upperNeedle.substr(key.length); - if (length < key.length && dir === "prev") - return key.substr(0, upperNeedle.length); - return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); - } - function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { - var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; - if (!needles.every(function (s) { return typeof s === 'string'; })) { - return fail(whereClause, STRING_EXPECTED); - } - function initDirection(dir) { - upper = upperFactory(dir); - lower = lowerFactory(dir); - compare = (dir === "next" ? simpleCompare : simpleCompareReverse); - var needleBounds = needles.map(function (needle) { - return { lower: lower(needle), upper: upper(needle) }; - }).sort(function (a, b) { - return compare(a.lower, b.lower); - }); - upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); - lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); - direction = dir; - nextKeySuffix = (dir === "next" ? "" : suffix); - } - initDirection("next"); - var c = new whereClause.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); - c._ondirectionchange = function (direction) { - initDirection(direction); - }; - var firstPossibleNeedle = 0; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - if (typeof key !== 'string') - return false; - var lowerKey = lower(key); - if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { - return true; - } - else { - var lowestPossibleCasing = null; - for (var i = firstPossibleNeedle; i < needlesLen; ++i) { - var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); - if (casing === null && lowestPossibleCasing === null) - firstPossibleNeedle = i + 1; - else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { - lowestPossibleCasing = casing; - } - } - if (lowestPossibleCasing !== null) { - advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); - } - else { - advance(resolve); - } - return false; - } - }); - return c; - } - function createRange(lower, upper, lowerOpen, upperOpen) { - return { - type: 2 , - lower: lower, - upper: upper, - lowerOpen: lowerOpen, - upperOpen: upperOpen - }; - } - function rangeEqual(value) { - return { - type: 1 , - lower: value, - upper: value - }; - } - - var WhereClause = (function () { - function WhereClause() { - } - Object.defineProperty(WhereClause.prototype, "Collection", { - get: function () { - return this._ctx.table.db.Collection; - }, - enumerable: false, - configurable: true - }); - WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { - includeLower = includeLower !== false; - includeUpper = includeUpper === true; - try { - if ((this._cmp(lower, upper) > 0) || - (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) - return emptyCollection(this); - return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - }; - WhereClause.prototype.equals = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return rangeEqual(value); }); - }; - WhereClause.prototype.above = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(value, undefined, true); }); - }; - WhereClause.prototype.aboveOrEqual = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(value, undefined, false); }); - }; - WhereClause.prototype.below = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); - }; - WhereClause.prototype.belowOrEqual = function (value) { - if (value == null) - return fail(this, INVALID_KEY_ARGUMENT); - return new this.Collection(this, function () { return createRange(undefined, value); }); - }; - WhereClause.prototype.startsWith = function (str) { - if (typeof str !== 'string') - return fail(this, STRING_EXPECTED); - return this.between(str, str + maxString, true, true); - }; - WhereClause.prototype.startsWithIgnoreCase = function (str) { - if (str === "") - return this.startsWith(str); - return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); - }; - WhereClause.prototype.equalsIgnoreCase = function (str) { - return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); - }; - WhereClause.prototype.anyOfIgnoreCase = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); - }; - WhereClause.prototype.startsWithAnyOfIgnoreCase = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return emptyCollection(this); - return addIgnoreCaseAlgorithm(this, function (x, a) { return a.some(function (n) { return x.indexOf(n) === 0; }); }, set, maxString); - }; - WhereClause.prototype.anyOf = function () { - var _this = this; - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - var compare = this._cmp; - try { - set.sort(compare); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - if (set.length === 0) - return emptyCollection(this); - var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); - c._ondirectionchange = function (direction) { - compare = (direction === "next" ? - _this._ascending : - _this._descending); - set.sort(compare); - }; - var i = 0; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - while (compare(key, set[i]) > 0) { - ++i; - if (i === set.length) { - advance(resolve); - return false; - } - } - if (compare(key, set[i]) === 0) { - return true; - } - else { - advance(function () { cursor.continue(set[i]); }); - return false; - } - }); - return c; - }; - WhereClause.prototype.notEqual = function (value) { - return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); - }; - WhereClause.prototype.noneOf = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (set.length === 0) - return new this.Collection(this); - try { - set.sort(this._ascending); - } - catch (e) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var ranges = set.reduce(function (res, val) { return res ? - res.concat([[res[res.length - 1][1], val]]) : - [[minKey, val]]; }, null); - ranges.push([set[set.length - 1], this.db._maxKey]); - return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); - }; - WhereClause.prototype.inAnyRange = function (ranges, options) { - var _this = this; - var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; - if (ranges.length === 0) - return emptyCollection(this); - if (!ranges.every(function (range) { - return range[0] !== undefined && - range[1] !== undefined && - ascending(range[0], range[1]) <= 0; - })) { - return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); - } - var includeLowers = !options || options.includeLowers !== false; - var includeUppers = options && options.includeUppers === true; - function addRange(ranges, newRange) { - var i = 0, l = ranges.length; - for (; i < l; ++i) { - var range = ranges[i]; - if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { - range[0] = min(range[0], newRange[0]); - range[1] = max(range[1], newRange[1]); - break; - } - } - if (i === l) - ranges.push(newRange); - return ranges; - } - var sortDirection = ascending; - function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } - var set; - try { - set = ranges.reduce(addRange, []); - set.sort(rangeSorter); - } - catch (ex) { - return fail(this, INVALID_KEY_ARGUMENT); - } - var rangePos = 0; - var keyIsBeyondCurrentEntry = includeUppers ? - function (key) { return ascending(key, set[rangePos][1]) > 0; } : - function (key) { return ascending(key, set[rangePos][1]) >= 0; }; - var keyIsBeforeCurrentEntry = includeLowers ? - function (key) { return descending(key, set[rangePos][0]) > 0; } : - function (key) { return descending(key, set[rangePos][0]) >= 0; }; - function keyWithinCurrentRange(key) { - return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); - } - var checkKey = keyIsBeyondCurrentEntry; - var c = new this.Collection(this, function () { return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); }); - c._ondirectionchange = function (direction) { - if (direction === "next") { - checkKey = keyIsBeyondCurrentEntry; - sortDirection = ascending; - } - else { - checkKey = keyIsBeforeCurrentEntry; - sortDirection = descending; - } - set.sort(rangeSorter); - }; - c._addAlgorithm(function (cursor, advance, resolve) { - var key = cursor.key; - while (checkKey(key)) { - ++rangePos; - if (rangePos === set.length) { - advance(resolve); - return false; - } - } - if (keyWithinCurrentRange(key)) { - return true; - } - else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { - return false; - } - else { - advance(function () { - if (sortDirection === ascending) - cursor.continue(set[rangePos][0]); - else - cursor.continue(set[rangePos][1]); - }); - return false; - } - }); - return c; - }; - WhereClause.prototype.startsWithAnyOf = function () { - var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); - if (!set.every(function (s) { return typeof s === 'string'; })) { - return fail(this, "startsWithAnyOf() only works with strings"); - } - if (set.length === 0) - return emptyCollection(this); - return this.inAnyRange(set.map(function (str) { return [str, str + maxString]; })); - }; - return WhereClause; - }()); - - function createWhereClauseConstructor(db) { - return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { - this.db = db; - this._ctx = { - table: table, - index: index === ":id" ? null : index, - or: orCollection - }; - this._cmp = this._ascending = cmp; - this._descending = function (a, b) { return cmp(b, a); }; - this._max = function (a, b) { return cmp(a, b) > 0 ? a : b; }; - this._min = function (a, b) { return cmp(a, b) < 0 ? a : b; }; - this._IDBKeyRange = db._deps.IDBKeyRange; - if (!this._IDBKeyRange) - throw new exceptions.MissingAPI(); - }); - } - - function eventRejectHandler(reject) { - return wrap(function (event) { - preventDefault(event); - reject(event.target.error); - return false; - }); - } - function preventDefault(event) { - if (event.stopPropagation) - event.stopPropagation(); - if (event.preventDefault) - event.preventDefault(); - } - - var DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; - var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; - var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); - - var Transaction = (function () { - function Transaction() { - } - Transaction.prototype._lock = function () { - assert(!PSD.global); - ++this._reculock; - if (this._reculock === 1 && !PSD.global) - PSD.lockOwnerFor = this; - return this; - }; - Transaction.prototype._unlock = function () { - assert(!PSD.global); - if (--this._reculock === 0) { - if (!PSD.global) - PSD.lockOwnerFor = null; - while (this._blockedFuncs.length > 0 && !this._locked()) { - var fnAndPSD = this._blockedFuncs.shift(); - try { - usePSD(fnAndPSD[1], fnAndPSD[0]); - } - catch (e) { } - } - } - return this; - }; - Transaction.prototype._locked = function () { - return this._reculock && PSD.lockOwnerFor !== this; - }; - Transaction.prototype.create = function (idbtrans) { - var _this = this; - if (!this.mode) - return this; - var idbdb = this.db.idbdb; - var dbOpenError = this.db._state.dbOpenError; - assert(!this.idbtrans); - if (!idbtrans && !idbdb) { - switch (dbOpenError && dbOpenError.name) { - case "DatabaseClosedError": - throw new exceptions.DatabaseClosed(dbOpenError); - case "MissingAPIError": - throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); - default: - throw new exceptions.OpenFailed(dbOpenError); - } - } - if (!this.active) - throw new exceptions.TransactionInactive(); - assert(this._completion._state === null); - idbtrans = this.idbtrans = idbtrans || - (this.db.core - ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) - : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); - idbtrans.onerror = wrap(function (ev) { - preventDefault(ev); - _this._reject(idbtrans.error); - }); - idbtrans.onabort = wrap(function (ev) { - preventDefault(ev); - _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); - _this.active = false; - _this.on("abort").fire(ev); - }); - idbtrans.oncomplete = wrap(function () { - _this.active = false; - _this._resolve(); - if ('mutatedParts' in idbtrans) { - globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); - } - }); - return this; - }; - Transaction.prototype._promise = function (mode, fn, bWriteLock) { - var _this = this; - if (mode === 'readwrite' && this.mode !== 'readwrite') - return rejection(new exceptions.ReadOnly("Transaction is readonly")); - if (!this.active) - return rejection(new exceptions.TransactionInactive()); - if (this._locked()) { - return new DexiePromise(function (resolve, reject) { - _this._blockedFuncs.push([function () { - _this._promise(mode, fn, bWriteLock).then(resolve, reject); - }, PSD]); - }); - } - else if (bWriteLock) { - return newScope(function () { - var p = new DexiePromise(function (resolve, reject) { - _this._lock(); - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p.finally(function () { return _this._unlock(); }); - p._lib = true; - return p; - }); - } - else { - var p = new DexiePromise(function (resolve, reject) { - var rv = fn(resolve, reject, _this); - if (rv && rv.then) - rv.then(resolve, reject); - }); - p._lib = true; - return p; - } - }; - Transaction.prototype._root = function () { - return this.parent ? this.parent._root() : this; - }; - Transaction.prototype.waitFor = function (promiseLike) { - var root = this._root(); - var promise = DexiePromise.resolve(promiseLike); - if (root._waitingFor) { - root._waitingFor = root._waitingFor.then(function () { return promise; }); - } - else { - root._waitingFor = promise; - root._waitingQueue = []; - var store = root.idbtrans.objectStore(root.storeNames[0]); - (function spin() { - ++root._spinCount; - while (root._waitingQueue.length) - (root._waitingQueue.shift())(); - if (root._waitingFor) - store.get(-Infinity).onsuccess = spin; - }()); - } - var currentWaitPromise = root._waitingFor; - return new DexiePromise(function (resolve, reject) { - promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { - if (root._waitingFor === currentWaitPromise) { - root._waitingFor = null; - } - }); - }); - }; - Transaction.prototype.abort = function () { - if (this.active) { - this.active = false; - if (this.idbtrans) - this.idbtrans.abort(); - this._reject(new exceptions.Abort()); - } - }; - Transaction.prototype.table = function (tableName) { - var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); - if (hasOwn(memoizedTables, tableName)) - return memoizedTables[tableName]; - var tableSchema = this.schema[tableName]; - if (!tableSchema) { - throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); - } - var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); - transactionBoundTable.core = this.db.core.table(tableName); - memoizedTables[tableName] = transactionBoundTable; - return transactionBoundTable; - }; - return Transaction; - }()); - - function createTransactionConstructor(db) { - return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { - var _this = this; - this.db = db; - this.mode = mode; - this.storeNames = storeNames; - this.schema = dbschema; - this.chromeTransactionDurability = chromeTransactionDurability; - this.idbtrans = null; - this.on = Events(this, "complete", "error", "abort"); - this.parent = parent || null; - this.active = true; - this._reculock = 0; - this._blockedFuncs = []; - this._resolve = null; - this._reject = null; - this._waitingFor = null; - this._waitingQueue = null; - this._spinCount = 0; - this._completion = new DexiePromise(function (resolve, reject) { - _this._resolve = resolve; - _this._reject = reject; - }); - this._completion.then(function () { - _this.active = false; - _this.on.complete.fire(); - }, function (e) { - var wasActive = _this.active; - _this.active = false; - _this.on.error.fire(e); - _this.parent ? - _this.parent._reject(e) : - wasActive && _this.idbtrans && _this.idbtrans.abort(); - return rejection(e); - }); - }); - } - - function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { - return { - name: name, - keyPath: keyPath, - unique: unique, - multi: multi, - auto: auto, - compound: compound, - src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) - }; - } - function nameFromKeyPath(keyPath) { - return typeof keyPath === 'string' ? - keyPath : - keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; - } - - function createTableSchema(name, primKey, indexes) { - return { - name: name, - primKey: primKey, - indexes: indexes, - mappedClass: null, - idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) - }; - } - - function safariMultiStoreFix(storeNames) { - return storeNames.length === 1 ? storeNames[0] : storeNames; - } - var getMaxKey = function (IdbKeyRange) { - try { - IdbKeyRange.only([[]]); - getMaxKey = function () { return [[]]; }; - return [[]]; - } - catch (e) { - getMaxKey = function () { return maxString; }; - return maxString; - } - }; - - function getKeyExtractor(keyPath) { - if (keyPath == null) { - return function () { return undefined; }; - } - else if (typeof keyPath === 'string') { - return getSinglePathKeyExtractor(keyPath); - } - else { - return function (obj) { return getByKeyPath(obj, keyPath); }; - } - } - function getSinglePathKeyExtractor(keyPath) { - var split = keyPath.split('.'); - if (split.length === 1) { - return function (obj) { return obj[keyPath]; }; - } - else { - return function (obj) { return getByKeyPath(obj, keyPath); }; - } - } - - function arrayify(arrayLike) { - return [].slice.call(arrayLike); - } - var _id_counter = 0; - function getKeyPathAlias(keyPath) { - return keyPath == null ? - ":id" : - typeof keyPath === 'string' ? - keyPath : - "[".concat(keyPath.join('+'), "]"); - } - function createDBCore(db, IdbKeyRange, tmpTrans) { - function extractSchema(db, trans) { - var tables = arrayify(db.objectStoreNames); - return { - schema: { - name: db.name, - tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { - var keyPath = store.keyPath, autoIncrement = store.autoIncrement; - var compound = isArray(keyPath); - var outbound = keyPath == null; - var indexByKeyPath = {}; - var result = { - name: store.name, - primaryKey: { - name: null, - isPrimaryKey: true, - outbound: outbound, - compound: compound, - keyPath: keyPath, - autoIncrement: autoIncrement, - unique: true, - extractKey: getKeyExtractor(keyPath) - }, - indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) - .map(function (index) { - var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; - var compound = isArray(keyPath); - var result = { - name: name, - compound: compound, - keyPath: keyPath, - unique: unique, - multiEntry: multiEntry, - extractKey: getKeyExtractor(keyPath) - }; - indexByKeyPath[getKeyPathAlias(keyPath)] = result; - return result; - }), - getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } - }; - indexByKeyPath[":id"] = result.primaryKey; - if (keyPath != null) { - indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; - } - return result; - }) - }, - hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && - !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && - !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && - [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) - }; - } - function makeIDBKeyRange(range) { - if (range.type === 3 ) - return null; - if (range.type === 4 ) - throw new Error("Cannot convert never type to IDBKeyRange"); - var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; - var idbRange = lower === undefined ? - upper === undefined ? - null : - IdbKeyRange.upperBound(upper, !!upperOpen) : - upper === undefined ? - IdbKeyRange.lowerBound(lower, !!lowerOpen) : - IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); - return idbRange; - } - function createDbCoreTable(tableSchema) { - var tableName = tableSchema.name; - function mutate(_a) { - var trans = _a.trans, type = _a.type, keys = _a.keys, values = _a.values, range = _a.range; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var outbound = store.keyPath == null; - var isAddOrPut = type === "put" || type === "add"; - if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') - throw new Error("Invalid operation type: " + type); - var length = (keys || values || { length: 1 }).length; - if (keys && values && keys.length !== values.length) { - throw new Error("Given keys array must have same length as given values array."); - } - if (length === 0) - return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); - var req; - var reqs = []; - var failures = []; - var numFailures = 0; - var errorHandler = function (event) { - ++numFailures; - preventDefault(event); - }; - if (type === 'deleteRange') { - if (range.type === 4 ) - return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); - if (range.type === 3 ) - reqs.push(req = store.clear()); - else - reqs.push(req = store.delete(makeIDBKeyRange(range))); - } - else { - var _a = isAddOrPut ? - outbound ? - [values, keys] : - [values, null] : - [keys, null], args1 = _a[0], args2 = _a[1]; - if (isAddOrPut) { - for (var i = 0; i < length; ++i) { - reqs.push(req = (args2 && args2[i] !== undefined ? - store[type](args1[i], args2[i]) : - store[type](args1[i]))); - req.onerror = errorHandler; - } - } - else { - for (var i = 0; i < length; ++i) { - reqs.push(req = store[type](args1[i])); - req.onerror = errorHandler; - } - } - } - var done = function (event) { - var lastResult = event.target.result; - reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); - resolve({ - numFailures: numFailures, - failures: failures, - results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), - lastResult: lastResult - }); - }; - req.onerror = function (event) { - errorHandler(event); - done(event); - }; - req.onsuccess = done; - }); - } - function openCursor(_a) { - var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var index = query.index, range = query.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? - store : - store.index(index.name); - var direction = reverse ? - unique ? - "prevunique" : - "prev" : - unique ? - "nextunique" : - "next"; - var req = values || !('openKeyCursor' in source) ? - source.openCursor(makeIDBKeyRange(range), direction) : - source.openKeyCursor(makeIDBKeyRange(range), direction); - req.onerror = eventRejectHandler(reject); - req.onsuccess = wrap(function (ev) { - var cursor = req.result; - if (!cursor) { - resolve(null); - return; - } - cursor.___id = ++_id_counter; - cursor.done = false; - var _cursorContinue = cursor.continue.bind(cursor); - var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; - if (_cursorContinuePrimaryKey) - _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); - var _cursorAdvance = cursor.advance.bind(cursor); - var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; - var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; - cursor.trans = trans; - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; - cursor.fail = wrap(reject); - cursor.next = function () { - var _this = this; - var gotOne = 1; - return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); - }; - cursor.start = function (callback) { - var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { - resolveIteration = wrap(resolveIteration); - req.onerror = eventRejectHandler(rejectIteration); - cursor.fail = rejectIteration; - cursor.stop = function (value) { - cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; - resolveIteration(value); - }; - }); - var guardedCallback = function () { - if (req.result) { - try { - callback(); - } - catch (err) { - cursor.fail(err); - } - } - else { - cursor.done = true; - cursor.start = function () { throw new Error("Cursor behind last entry"); }; - cursor.stop(); - } - }; - req.onsuccess = wrap(function (ev) { - req.onsuccess = guardedCallback; - guardedCallback(); - }); - cursor.continue = _cursorContinue; - cursor.continuePrimaryKey = _cursorContinuePrimaryKey; - cursor.advance = _cursorAdvance; - guardedCallback(); - return iterationPromise; - }; - resolve(cursor); - }, reject); - }); - } - function query(hasGetAll) { - return function (request) { - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var trans = request.trans, values = request.values, limit = request.limit, query = request.query; - var nonInfinitLimit = limit === Infinity ? undefined : limit; - var index = query.index, range = query.range; - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - if (limit === 0) - return resolve({ result: [] }); - if (hasGetAll) { - var req = values ? - source.getAll(idbKeyRange, nonInfinitLimit) : - source.getAllKeys(idbKeyRange, nonInfinitLimit); - req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; - req.onerror = eventRejectHandler(reject); - } - else { - var count_1 = 0; - var req_1 = values || !('openKeyCursor' in source) ? - source.openCursor(idbKeyRange) : - source.openKeyCursor(idbKeyRange); - var result_1 = []; - req_1.onsuccess = function (event) { - var cursor = req_1.result; - if (!cursor) - return resolve({ result: result_1 }); - result_1.push(values ? cursor.value : cursor.primaryKey); - if (++count_1 === limit) - return resolve({ result: result_1 }); - cursor.continue(); - }; - req_1.onerror = eventRejectHandler(reject); - } - }); - }; - } - return { - name: tableName, - schema: tableSchema, - mutate: mutate, - getMany: function (_a) { - var trans = _a.trans, keys = _a.keys; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var length = keys.length; - var result = new Array(length); - var keyCount = 0; - var callbackCount = 0; - var req; - var successHandler = function (event) { - var req = event.target; - if ((result[req._pos] = req.result) != null) - ; - if (++callbackCount === keyCount) - resolve(result); - }; - var errorHandler = eventRejectHandler(reject); - for (var i = 0; i < length; ++i) { - var key = keys[i]; - if (key != null) { - req = store.get(keys[i]); - req._pos = i; - req.onsuccess = successHandler; - req.onerror = errorHandler; - ++keyCount; - } - } - if (keyCount === 0) - resolve(result); - }); - }, - get: function (_a) { - var trans = _a.trans, key = _a.key; - return new Promise(function (resolve, reject) { - resolve = wrap(resolve); - var store = trans.objectStore(tableName); - var req = store.get(key); - req.onsuccess = function (event) { return resolve(event.target.result); }; - req.onerror = eventRejectHandler(reject); - }); - }, - query: query(hasGetAll), - openCursor: openCursor, - count: function (_a) { - var query = _a.query, trans = _a.trans; - var index = query.index, range = query.range; - return new Promise(function (resolve, reject) { - var store = trans.objectStore(tableName); - var source = index.isPrimaryKey ? store : store.index(index.name); - var idbKeyRange = makeIDBKeyRange(range); - var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); - req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); - req.onerror = eventRejectHandler(reject); - }); - } - }; - } - var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; - var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); - var tableMap = {}; - tables.forEach(function (table) { return tableMap[table.name] = table; }); - return { - stack: "dbcore", - transaction: db.transaction.bind(db), - table: function (name) { - var result = tableMap[name]; - if (!result) - throw new Error("Table '".concat(name, "' not found")); - return tableMap[name]; - }, - MIN_KEY: -Infinity, - MAX_KEY: getMaxKey(IdbKeyRange), - schema: schema - }; - } - - function createMiddlewareStack(stackImpl, middlewares) { - return middlewares.reduce(function (down, _a) { - var create = _a.create; - return (__assign(__assign({}, down), create(down))); - }, stackImpl); - } - function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { - var IDBKeyRange = _a.IDBKeyRange; _a.indexedDB; - var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); - return { - dbcore: dbcore - }; - } - function generateMiddlewareStacks(db, tmpTrans) { - var idbdb = tmpTrans.db; - var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); - db.core = stacks.dbcore; - db.tables.forEach(function (table) { - var tableName = table.name; - if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { - table.core = db.core.table(tableName); - if (db[tableName] instanceof db.Table) { - db[tableName].core = table.core; - } - } - }); - } - - function setApiOnPlace(db, objs, tableNames, dbschema) { - tableNames.forEach(function (tableName) { - var schema = dbschema[tableName]; - objs.forEach(function (obj) { - var propDesc = getPropertyDescriptor(obj, tableName); - if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { - if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { - setProp(obj, tableName, { - get: function () { return this.table(tableName); }, - set: function (value) { - defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); - } - }); - } - else { - obj[tableName] = new db.Table(tableName, schema); - } - } - }); - }); - } - function removeTablesApi(db, objs) { - objs.forEach(function (obj) { - for (var key in obj) { - if (obj[key] instanceof db.Table) - delete obj[key]; - } - }); - } - function lowerVersionFirst(a, b) { - return a._cfg.version - b._cfg.version; - } - function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { - var globalSchema = db._dbSchema; - if (idbUpgradeTrans.objectStoreNames.contains('$meta') && !globalSchema.$meta) { - globalSchema.$meta = createTableSchema("$meta", parseIndexSyntax("")[0], []); - db._storeNames.push('$meta'); - } - var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); - trans.create(idbUpgradeTrans); - trans._completion.catch(reject); - var rejectTransaction = trans._reject.bind(trans); - var transless = PSD.transless || PSD; - newScope(function () { - PSD.trans = trans; - PSD.transless = transless; - if (oldVersion === 0) { - keys(globalSchema).forEach(function (tableName) { - createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); - }); - generateMiddlewareStacks(db, idbUpgradeTrans); - DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); - } - else { - generateMiddlewareStacks(db, idbUpgradeTrans); - return getExistingVersion(db, trans, oldVersion) - .then(function (oldVersion) { return updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans); }) - .catch(rejectTransaction); - } - }); - } - function patchCurrentVersion(db, idbUpgradeTrans) { - createMissingTables(db._dbSchema, idbUpgradeTrans); - if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) { - idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version'); - } - var globalSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); - adjustToExistingIndexNames(db, db._dbSchema, idbUpgradeTrans); - var diff = getSchemaDiff(globalSchema, db._dbSchema); - var _loop_1 = function (tableChange) { - if (tableChange.change.length || tableChange.recreate) { - console.warn("Unable to patch indexes of table ".concat(tableChange.name, " because it has changes on the type of index or primary key.")); - return { value: void 0 }; - } - var store = idbUpgradeTrans.objectStore(tableChange.name); - tableChange.add.forEach(function (idx) { - if (debug) - console.debug("Dexie upgrade patch: Creating missing index ".concat(tableChange.name, ".").concat(idx.src)); - addIndex(store, idx); - }); - }; - for (var _i = 0, _a = diff.change; _i < _a.length; _i++) { - var tableChange = _a[_i]; - var state_1 = _loop_1(tableChange); - if (typeof state_1 === "object") - return state_1.value; - } - } - function getExistingVersion(db, trans, oldVersion) { - if (trans.storeNames.includes('$meta')) { - return trans.table('$meta').get('version').then(function (metaVersion) { - return metaVersion != null ? metaVersion : oldVersion; - }); - } - else { - return DexiePromise.resolve(oldVersion); - } - } - function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { - var queue = []; - var versions = db._versions; - var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); - var versToRun = versions.filter(function (v) { return v._cfg.version >= oldVersion; }); - if (versToRun.length === 0) { - return DexiePromise.resolve(); - } - versToRun.forEach(function (version) { - queue.push(function () { - var oldSchema = globalSchema; - var newSchema = version._cfg.dbschema; - adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans); - adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); - globalSchema = db._dbSchema = newSchema; - var diff = getSchemaDiff(oldSchema, newSchema); - diff.add.forEach(function (tuple) { - createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); - }); - diff.change.forEach(function (change) { - if (change.recreate) { - throw new exceptions.Upgrade("Not yet support for changing primary key"); - } - else { - var store_1 = idbUpgradeTrans.objectStore(change.name); - change.add.forEach(function (idx) { return addIndex(store_1, idx); }); - change.change.forEach(function (idx) { - store_1.deleteIndex(idx.name); - addIndex(store_1, idx); - }); - change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); - } - }); - var contentUpgrade = version._cfg.contentUpgrade; - if (contentUpgrade && version._cfg.version > oldVersion) { - generateMiddlewareStacks(db, idbUpgradeTrans); - trans._memoizedTables = {}; - var upgradeSchema_1 = shallowClone(newSchema); - diff.del.forEach(function (table) { - upgradeSchema_1[table] = oldSchema[table]; - }); - removeTablesApi(db, [db.Transaction.prototype]); - setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); - trans.schema = upgradeSchema_1; - var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); - if (contentUpgradeIsAsync_1) { - incrementExpectedAwaits(); - } - var returnValue_1; - var promiseFollowed = DexiePromise.follow(function () { - returnValue_1 = contentUpgrade(trans); - if (returnValue_1) { - if (contentUpgradeIsAsync_1) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue_1.then(decrementor, decrementor); - } - } - }); - return (returnValue_1 && typeof returnValue_1.then === 'function' ? - DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); - } - }); - queue.push(function (idbtrans) { - var newSchema = version._cfg.dbschema; - deleteRemovedTables(newSchema, idbtrans); - removeTablesApi(db, [db.Transaction.prototype]); - setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); - trans.schema = db._dbSchema; - }); - queue.push(function (idbtrans) { - if (db.idbdb.objectStoreNames.contains('$meta')) { - if (Math.ceil(db.idbdb.version / 10) === version._cfg.version) { - db.idbdb.deleteObjectStore('$meta'); - delete db._dbSchema.$meta; - db._storeNames = db._storeNames.filter(function (name) { return name !== '$meta'; }); - } - else { - idbtrans.objectStore('$meta').put(version._cfg.version, 'version'); - } - } - }); - }); - function runQueue() { - return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : - DexiePromise.resolve(); - } - return runQueue().then(function () { - createMissingTables(globalSchema, idbUpgradeTrans); - }); - } - function getSchemaDiff(oldSchema, newSchema) { - var diff = { - del: [], - add: [], - change: [] - }; - var table; - for (table in oldSchema) { - if (!newSchema[table]) - diff.del.push(table); - } - for (table in newSchema) { - var oldDef = oldSchema[table], newDef = newSchema[table]; - if (!oldDef) { - diff.add.push([table, newDef]); - } - else { - var change = { - name: table, - def: newDef, - recreate: false, - del: [], - add: [], - change: [] - }; - if (( - '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || - (oldDef.primKey.auto !== newDef.primKey.auto)) { - change.recreate = true; - diff.change.push(change); - } - else { - var oldIndexes = oldDef.idxByName; - var newIndexes = newDef.idxByName; - var idxName = void 0; - for (idxName in oldIndexes) { - if (!newIndexes[idxName]) - change.del.push(idxName); - } - for (idxName in newIndexes) { - var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; - if (!oldIdx) - change.add.push(newIdx); - else if (oldIdx.src !== newIdx.src) - change.change.push(newIdx); - } - if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { - diff.change.push(change); - } - } - } - } - return diff; - } - function createTable(idbtrans, tableName, primKey, indexes) { - var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? - { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : - { autoIncrement: primKey.auto }); - indexes.forEach(function (idx) { return addIndex(store, idx); }); - return store; - } - function createMissingTables(newSchema, idbtrans) { - keys(newSchema).forEach(function (tableName) { - if (!idbtrans.db.objectStoreNames.contains(tableName)) { - if (debug) - console.debug('Dexie: Creating missing table', tableName); - createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); - } - }); - } - function deleteRemovedTables(newSchema, idbtrans) { - [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { - return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); - }); - } - function addIndex(store, idx) { - store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); - } - function buildGlobalSchema(db, idbdb, tmpTrans) { - var globalSchema = {}; - var dbStoreNames = slice(idbdb.objectStoreNames, 0); - dbStoreNames.forEach(function (storeName) { - var store = tmpTrans.objectStore(storeName); - var keyPath = store.keyPath; - var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); - var indexes = []; - for (var j = 0; j < store.indexNames.length; ++j) { - var idbindex = store.index(store.indexNames[j]); - keyPath = idbindex.keyPath; - var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); - indexes.push(index); - } - globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); - }); - return globalSchema; - } - function readGlobalSchema(db, idbdb, tmpTrans) { - db.verno = idbdb.version / 10; - var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); - db._storeNames = slice(idbdb.objectStoreNames, 0); - setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); - } - function verifyInstalledSchema(db, tmpTrans) { - var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); - var diff = getSchemaDiff(installedSchema, db._dbSchema); - return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); - } - function adjustToExistingIndexNames(db, schema, idbtrans) { - var storeNames = idbtrans.db.objectStoreNames; - for (var i = 0; i < storeNames.length; ++i) { - var storeName = storeNames[i]; - var store = idbtrans.objectStore(storeName); - db._hasGetAll = 'getAll' in store; - for (var j = 0; j < store.indexNames.length; ++j) { - var indexName = store.indexNames[j]; - var keyPath = store.index(indexName).keyPath; - var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; - if (schema[storeName]) { - var indexSpec = schema[storeName].idxByName[dexieName]; - if (indexSpec) { - indexSpec.name = indexName; - delete schema[storeName].idxByName[dexieName]; - schema[storeName].idxByName[indexName] = indexSpec; - } - } - } - } - if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && - !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && - _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && - [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { - db._hasGetAll = false; - } - } - function parseIndexSyntax(primKeyAndIndexes) { - return primKeyAndIndexes.split(',').map(function (index, indexNum) { - index = index.trim(); - var name = index.replace(/([&*]|\+\+)/g, ""); - var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; - return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); - }); - } - - var Version = (function () { - function Version() { - } - Version.prototype._parseStoresSpec = function (stores, outSchema) { - keys(stores).forEach(function (tableName) { - if (stores[tableName] !== null) { - var indexes = parseIndexSyntax(stores[tableName]); - var primKey = indexes.shift(); - primKey.unique = true; - if (primKey.multi) - throw new exceptions.Schema("Primary key cannot be multi-valued"); - indexes.forEach(function (idx) { - if (idx.auto) - throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); - if (!idx.keyPath) - throw new exceptions.Schema("Index must have a name and cannot be an empty string"); - }); - outSchema[tableName] = createTableSchema(tableName, primKey, indexes); - } - }); - }; - Version.prototype.stores = function (stores) { - var db = this.db; - this._cfg.storesSource = this._cfg.storesSource ? - extend(this._cfg.storesSource, stores) : - stores; - var versions = db._versions; - var storesSpec = {}; - var dbschema = {}; - versions.forEach(function (version) { - extend(storesSpec, version._cfg.storesSource); - dbschema = (version._cfg.dbschema = {}); - version._parseStoresSpec(storesSpec, dbschema); - }); - db._dbSchema = dbschema; - removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); - setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); - db._storeNames = keys(dbschema); - return this; - }; - Version.prototype.upgrade = function (upgradeFunction) { - this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); - return this; - }; - return Version; - }()); - - function createVersionConstructor(db) { - return makeClassConstructor(Version.prototype, function Version(versionNumber) { - this.db = db; - this._cfg = { - version: versionNumber, - storesSource: null, - dbschema: {}, - tables: {}, - contentUpgrade: null - }; - }); - } - - function getDbNamesTable(indexedDB, IDBKeyRange) { - var dbNamesDB = indexedDB["_dbNamesDB"]; - if (!dbNamesDB) { - dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { - addons: [], - indexedDB: indexedDB, - IDBKeyRange: IDBKeyRange, - }); - dbNamesDB.version(1).stores({ dbnames: "name" }); - } - return dbNamesDB.table("dbnames"); - } - function hasDatabasesNative(indexedDB) { - return indexedDB && typeof indexedDB.databases === "function"; - } - function getDatabaseNames(_a) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - return hasDatabasesNative(indexedDB) - ? Promise.resolve(indexedDB.databases()).then(function (infos) { - return infos - .map(function (info) { return info.name; }) - .filter(function (name) { return name !== DBNAMES_DB; }); - }) - : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); - } - function _onDatabaseCreated(_a, name) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - !hasDatabasesNative(indexedDB) && - name !== DBNAMES_DB && - getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); - } - function _onDatabaseDeleted(_a, name) { - var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; - !hasDatabasesNative(indexedDB) && - name !== DBNAMES_DB && - getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); - } - - function vip(fn) { - return newScope(function () { - PSD.letThrough = true; - return fn(); - }); - } - - function idbReady() { - var isSafari = !navigator.userAgentData && - /Safari\//.test(navigator.userAgent) && - !/Chrom(e|ium)\//.test(navigator.userAgent); - if (!isSafari || !indexedDB.databases) - return Promise.resolve(); - var intervalId; - return new Promise(function (resolve) { - var tryIdb = function () { return indexedDB.databases().finally(resolve); }; - intervalId = setInterval(tryIdb, 100); - tryIdb(); - }).finally(function () { return clearInterval(intervalId); }); - } - - var _a; - function isEmptyRange(node) { - return !("from" in node); - } - var RangeSet = function (fromOrTree, to) { - if (this) { - extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); - } - else { - var rv = new RangeSet(); - if (fromOrTree && ("d" in fromOrTree)) { - extend(rv, fromOrTree); - } - return rv; - } - }; - props(RangeSet.prototype, (_a = { - add: function (rangeSet) { - mergeRanges(this, rangeSet); - return this; - }, - addKey: function (key) { - addRange(this, key, key); - return this; - }, - addKeys: function (keys) { - var _this = this; - keys.forEach(function (key) { return addRange(_this, key, key); }); - return this; - } - }, - _a[iteratorSymbol] = function () { - return getRangeSetIterator(this); - }, - _a)); - function addRange(target, from, to) { - var diff = cmp(from, to); - if (isNaN(diff)) - return; - if (diff > 0) - throw RangeError(); - if (isEmptyRange(target)) - return extend(target, { from: from, to: to, d: 1 }); - var left = target.l; - var right = target.r; - if (cmp(to, target.from) < 0) { - left - ? addRange(left, from, to) - : (target.l = { from: from, to: to, d: 1, l: null, r: null }); - return rebalance(target); - } - if (cmp(from, target.to) > 0) { - right - ? addRange(right, from, to) - : (target.r = { from: from, to: to, d: 1, l: null, r: null }); - return rebalance(target); - } - if (cmp(from, target.from) < 0) { - target.from = from; - target.l = null; - target.d = right ? right.d + 1 : 1; - } - if (cmp(to, target.to) > 0) { - target.to = to; - target.r = null; - target.d = target.l ? target.l.d + 1 : 1; - } - var rightWasCutOff = !target.r; - if (left && !target.l) { - mergeRanges(target, left); - } - if (right && rightWasCutOff) { - mergeRanges(target, right); - } - } - function mergeRanges(target, newSet) { - function _addRangeSet(target, _a) { - var from = _a.from, to = _a.to, l = _a.l, r = _a.r; - addRange(target, from, to); - if (l) - _addRangeSet(target, l); - if (r) - _addRangeSet(target, r); - } - if (!isEmptyRange(newSet)) - _addRangeSet(target, newSet); - } - function rangesOverlap(rangeSet1, rangeSet2) { - var i1 = getRangeSetIterator(rangeSet2); - var nextResult1 = i1.next(); - if (nextResult1.done) - return false; - var a = nextResult1.value; - var i2 = getRangeSetIterator(rangeSet1); - var nextResult2 = i2.next(a.from); - var b = nextResult2.value; - while (!nextResult1.done && !nextResult2.done) { - if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) - return true; - cmp(a.from, b.from) < 0 - ? (a = (nextResult1 = i1.next(b.from)).value) - : (b = (nextResult2 = i2.next(a.from)).value); - } - return false; - } - function getRangeSetIterator(node) { - var state = isEmptyRange(node) ? null : { s: 0, n: node }; - return { - next: function (key) { - var keyProvided = arguments.length > 0; - while (state) { - switch (state.s) { - case 0: - state.s = 1; - if (keyProvided) { - while (state.n.l && cmp(key, state.n.from) < 0) - state = { up: state, n: state.n.l, s: 1 }; - } - else { - while (state.n.l) - state = { up: state, n: state.n.l, s: 1 }; - } - case 1: - state.s = 2; - if (!keyProvided || cmp(key, state.n.to) <= 0) - return { value: state.n, done: false }; - case 2: - if (state.n.r) { - state.s = 3; - state = { up: state, n: state.n.r, s: 0 }; - continue; - } - case 3: - state = state.up; - } - } - return { done: true }; - }, - }; - } - function rebalance(target) { - var _a, _b; - var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); - var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; - if (r) { - var l = r === "r" ? "l" : "r"; - var rootClone = __assign({}, target); - var oldRootRight = target[r]; - target.from = oldRootRight.from; - target.to = oldRootRight.to; - target[r] = oldRootRight[r]; - rootClone[r] = oldRootRight[l]; - target[l] = rootClone; - rootClone.d = computeDepth(rootClone); - } - target.d = computeDepth(target); - } - function computeDepth(_a) { - var r = _a.r, l = _a.l; - return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; - } - - function extendObservabilitySet(target, newSet) { - keys(newSet).forEach(function (part) { - if (target[part]) - mergeRanges(target[part], newSet[part]); - else - target[part] = cloneSimpleObjectTree(newSet[part]); - }); - return target; - } - - function obsSetsOverlap(os1, os2) { - return os1.all || os2.all || Object.keys(os1).some(function (key) { return os2[key] && rangesOverlap(os2[key], os1[key]); }); - } - - var cache = {}; - - var unsignaledParts = {}; - var isTaskEnqueued = false; - function signalSubscribersLazily(part, optimistic) { - extendObservabilitySet(unsignaledParts, part); - if (!isTaskEnqueued) { - isTaskEnqueued = true; - setTimeout(function () { - isTaskEnqueued = false; - var parts = unsignaledParts; - unsignaledParts = {}; - signalSubscribersNow(parts, false); - }, 0); - } - } - function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { - if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; } - var queriesToSignal = new Set(); - if (updatedParts.all) { - for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) { - var tblCache = _a[_i]; - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - else { - for (var key in updatedParts) { - var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); - if (parts) { - var dbName = parts[1], tableName = parts[2]; - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (tblCache) - collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); - } - } - } - queriesToSignal.forEach(function (requery) { return requery(); }); - } - function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { - var updatedEntryLists = []; - for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) { - var _b = _a[_i], indexName = _b[0], entries = _b[1]; - var filteredEntries = []; - for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { - var entry = entries_1[_c]; - if (obsSetsOverlap(updatedParts, entry.obsSet)) { - entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); }); - } - else if (deleteAffectedCacheEntries) { - filteredEntries.push(entry); - } - } - if (deleteAffectedCacheEntries) - updatedEntryLists.push([indexName, filteredEntries]); - } - if (deleteAffectedCacheEntries) { - for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { - var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; - tblCache.queries.query[indexName] = filteredEntries; - } - } - } - - function dexieOpen(db) { - var state = db._state; - var indexedDB = db._deps.indexedDB; - if (state.isBeingOpened || db.idbdb) - return state.dbReadyPromise.then(function () { return state.dbOpenError ? - rejection(state.dbOpenError) : - db; }); - state.isBeingOpened = true; - state.dbOpenError = null; - state.openComplete = false; - var openCanceller = state.openCanceller; - var nativeVerToOpen = Math.round(db.verno * 10); - var schemaPatchMode = false; - function throwIfCancelled() { - if (state.openCanceller !== openCanceller) - throw new exceptions.DatabaseClosed('db.open() was cancelled'); - } - var resolveDbReady = state.dbReadyResolve, - upgradeTransaction = null, wasCreated = false; - var tryOpenDB = function () { return new DexiePromise(function (resolve, reject) { - throwIfCancelled(); - if (!indexedDB) - throw new exceptions.MissingAPI(); - var dbName = db.name; - var req = state.autoSchema || !nativeVerToOpen ? - indexedDB.open(dbName) : - indexedDB.open(dbName, nativeVerToOpen); - if (!req) - throw new exceptions.MissingAPI(); - req.onerror = eventRejectHandler(reject); - req.onblocked = wrap(db._fireOnBlocked); - req.onupgradeneeded = wrap(function (e) { - upgradeTransaction = req.transaction; - if (state.autoSchema && !db._options.allowEmptyDB) { - req.onerror = preventDefault; - upgradeTransaction.abort(); - req.result.close(); - var delreq = indexedDB.deleteDatabase(dbName); - delreq.onsuccess = delreq.onerror = wrap(function () { - reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); - }); - } - else { - upgradeTransaction.onerror = eventRejectHandler(reject); - var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; - wasCreated = oldVer < 1; - db.idbdb = req.result; - if (schemaPatchMode) { - patchCurrentVersion(db, upgradeTransaction); - } - runUpgraders(db, oldVer / 10, upgradeTransaction, reject); - } - }, reject); - req.onsuccess = wrap(function () { - upgradeTransaction = null; - var idbdb = db.idbdb = req.result; - var objectStoreNames = slice(idbdb.objectStoreNames); - if (objectStoreNames.length > 0) - try { - var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); - if (state.autoSchema) - readGlobalSchema(db, idbdb, tmpTrans); - else { - adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); - if (!verifyInstalledSchema(db, tmpTrans) && !schemaPatchMode) { - 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."); - idbdb.close(); - nativeVerToOpen = idbdb.version + 1; - schemaPatchMode = true; - return resolve(tryOpenDB()); - } - } - generateMiddlewareStacks(db, tmpTrans); - } - catch (e) { - } - connections.push(db); - idbdb.onversionchange = wrap(function (ev) { - state.vcFired = true; - db.on("versionchange").fire(ev); - }); - idbdb.onclose = wrap(function (ev) { - db.on("close").fire(ev); - }); - if (wasCreated) - _onDatabaseCreated(db._deps, dbName); - resolve(); - }, reject); - }).catch(function (err) { - switch (err === null || err === void 0 ? void 0 : err.name) { - case "UnknownError": - if (state.PR1398_maxLoop > 0) { - state.PR1398_maxLoop--; - console.warn('Dexie: Workaround for Chrome UnknownError on open()'); - return tryOpenDB(); - } - break; - case "VersionError": - if (nativeVerToOpen > 0) { - nativeVerToOpen = 0; - return tryOpenDB(); - } - break; - } - return DexiePromise.reject(err); - }); }; - return DexiePromise.race([ - openCanceller, - (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) - ]).then(function () { - throwIfCancelled(); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { - if (state.onReadyBeingFired.length > 0) { - var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); - state.onReadyBeingFired = []; - return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); - } - }); - }).finally(function () { - if (state.openCanceller === openCanceller) { - state.onReadyBeingFired = null; - state.isBeingOpened = false; - } - }).catch(function (err) { - state.dbOpenError = err; - try { - upgradeTransaction && upgradeTransaction.abort(); - } - catch (_a) { } - if (openCanceller === state.openCanceller) { - db._close(); - } - return rejection(err); - }).finally(function () { - state.openComplete = true; - resolveDbReady(); - }).then(function () { - if (wasCreated) { - var everything_1 = {}; - db.tables.forEach(function (table) { - table.schema.indexes.forEach(function (idx) { - if (idx.name) - everything_1["idb://".concat(db.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet(-Infinity, [[[]]]); - }); - everything_1["idb://".concat(db.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db.name, "/").concat(table.name, "/:dels")] = new RangeSet(-Infinity, [[[]]]); - }); - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); - signalSubscribersNow(everything_1, true); - } - return db; - }); - } - - function awaitIterator(iterator) { - var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); - function step(getNext) { - return function (val) { - var next = getNext(val), value = next.value; - return next.done ? value : - (!value || typeof value.then !== 'function' ? - isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : - value.then(onSuccess, onError)); - }; - } - return step(callNext)(); - } - - function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { - var i = arguments.length; - if (i < 2) - throw new exceptions.InvalidArgument("Too few arguments"); - var args = new Array(i - 1); - while (--i) - args[i - 1] = arguments[i]; - scopeFunc = args.pop(); - var tables = flatten(args); - return [mode, tables, scopeFunc]; - } - function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { - return DexiePromise.resolve().then(function () { - var transless = PSD.transless || PSD; - var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); - trans.explicit = true; - var zoneProps = { - trans: trans, - transless: transless - }; - if (parentTransaction) { - trans.idbtrans = parentTransaction.idbtrans; - } - else { - try { - trans.create(); - trans.idbtrans._explicit = true; - db._state.PR1398_maxLoop = 3; - } - catch (ex) { - if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { - console.warn('Dexie: Need to reopen db'); - db.close({ disableAutoOpen: false }); - return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); - } - return rejection(ex); - } - } - var scopeFuncIsAsync = isAsyncFunction(scopeFunc); - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var returnValue; - var promiseFollowed = DexiePromise.follow(function () { - returnValue = scopeFunc.call(trans, trans); - if (returnValue) { - if (scopeFuncIsAsync) { - var decrementor = decrementExpectedAwaits.bind(null, null); - returnValue.then(decrementor, decrementor); - } - else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { - returnValue = awaitIterator(returnValue); - } - } - }, zoneProps); - return (returnValue && typeof returnValue.then === 'function' ? - DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? - x - : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) - : promiseFollowed.then(function () { return returnValue; })).then(function (x) { - if (parentTransaction) - trans._resolve(); - return trans._completion.then(function () { return x; }); - }).catch(function (e) { - trans._reject(e); - return rejection(e); - }); - }); - } - - function pad(a, value, count) { - var result = isArray(a) ? a.slice() : [a]; - for (var i = 0; i < count; ++i) - result.push(value); - return result; - } - function createVirtualIndexMiddleware(down) { - return __assign(__assign({}, down), { table: function (tableName) { - var table = down.table(tableName); - var schema = table.schema; - var indexLookup = {}; - var allVirtualIndexes = []; - function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { - var keyPathAlias = getKeyPathAlias(keyPath); - var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); - var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; - var isVirtual = keyTail > 0; - var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual - ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") - : lowLevelIndex.name, lowLevelIndex: lowLevelIndex, isVirtual: isVirtual, keyTail: keyTail, keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); - indexList.push(virtualIndex); - if (!virtualIndex.isPrimaryKey) { - allVirtualIndexes.push(virtualIndex); - } - if (keyLength > 1) { - var virtualKeyPath = keyLength === 2 ? - keyPath[0] : - keyPath.slice(0, keyLength - 1); - addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); - } - indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); - return virtualIndex; - } - var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); - indexLookup[":id"] = [primaryKey]; - for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { - var index = _a[_i]; - addVirtualIndexes(index.keyPath, 0, index); - } - function findBestIndex(keyPath) { - var result = indexLookup[getKeyPathAlias(keyPath)]; - return result && result[0]; - } - function translateRange(range, keyTail) { - return { - type: range.type === 1 ? - 2 : - range.type, - lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), - lowerOpen: true, - upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), - upperOpen: true - }; - } - function translateRequest(req) { - var index = req.query.index; - return index.isVirtual ? __assign(__assign({}, req), { query: { - index: index.lowLevelIndex, - range: translateRange(req.query.range, index.keyTail) - } }) : req; - } - var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { - return table.count(translateRequest(req)); - }, query: function (req) { - return table.query(translateRequest(req)); - }, openCursor: function (req) { - var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; - if (!isVirtual) - return table.openCursor(req); - function createVirtualCursor(cursor) { - function _continue(key) { - key != null ? - cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : - req.unique ? - cursor.continue(cursor.key.slice(0, keyLength) - .concat(req.reverse - ? down.MIN_KEY - : down.MAX_KEY, keyTail)) : - cursor.continue(); - } - var virtualCursor = Object.create(cursor, { - continue: { value: _continue }, - continuePrimaryKey: { - value: function (key, primaryKey) { - cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); - } - }, - primaryKey: { - get: function () { - return cursor.primaryKey; - } - }, - key: { - get: function () { - var key = cursor.key; - return keyLength === 1 ? - key[0] : - key.slice(0, keyLength); - } - }, - value: { - get: function () { - return cursor.value; - } - } - }); - return virtualCursor; - } - return table.openCursor(translateRequest(req)) - .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); - } }); - return result; - } }); - } - var virtualIndexMiddleware = { - stack: "dbcore", - name: "VirtualIndexMiddleware", - level: 1, - create: createVirtualIndexMiddleware - }; - - function getObjectDiff(a, b, rv, prfx) { - rv = rv || {}; - prfx = prfx || ''; - keys(a).forEach(function (prop) { - if (!hasOwn(b, prop)) { - rv[prfx + prop] = undefined; - } - else { - var ap = a[prop], bp = b[prop]; - if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { - var apTypeName = toStringTag(ap); - var bpTypeName = toStringTag(bp); - if (apTypeName !== bpTypeName) { - rv[prfx + prop] = b[prop]; - } - else if (apTypeName === 'Object') { - getObjectDiff(ap, bp, rv, prfx + prop + '.'); - } - else if (ap !== bp) { - rv[prfx + prop] = b[prop]; - } - } - else if (ap !== bp) - rv[prfx + prop] = b[prop]; - } - }); - keys(b).forEach(function (prop) { - if (!hasOwn(a, prop)) { - rv[prfx + prop] = b[prop]; - } - }); - return rv; - } - - function getEffectiveKeys(primaryKey, req) { - if (req.type === 'delete') - return req.keys; - return req.keys || req.values.map(primaryKey.extractKey); - } - - var hooksMiddleware = { - stack: "dbcore", - name: "HooksMiddleware", - level: 2, - create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { - var downTable = downCore.table(tableName); - var primaryKey = downTable.schema.primaryKey; - var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { - var dxTrans = PSD.trans; - var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; - switch (req.type) { - case 'add': - if (creating.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'put': - if (creating.fire === nop && updating.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'delete': - if (deleting.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); - case 'deleteRange': - if (deleting.fire === nop) - break; - return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); - } - return downTable.mutate(req); - function addPutOrDelete(req) { - var dxTrans = PSD.trans; - var keys = req.keys || getEffectiveKeys(primaryKey, req); - if (!keys) - throw new Error("Keys missing"); - req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); - if (req.type !== 'delete') - req.values = __spreadArray([], req.values, true); - if (req.keys) - req.keys = __spreadArray([], req.keys, true); - return getExistingValues(downTable, req, keys).then(function (existingValues) { - var contexts = keys.map(function (key, i) { - var existingValue = existingValues[i]; - var ctx = { onerror: null, onsuccess: null }; - if (req.type === 'delete') { - deleting.fire.call(ctx, key, existingValue, dxTrans); - } - else if (req.type === 'add' || existingValue === undefined) { - var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); - if (key == null && generatedPrimaryKey != null) { - key = generatedPrimaryKey; - req.keys[i] = key; - if (!primaryKey.outbound) { - setByKeyPath(req.values[i], primaryKey.keyPath, key); - } - } - } - else { - var objectDiff = getObjectDiff(existingValue, req.values[i]); - var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); - if (additionalChanges_1) { - var requestedValue_1 = req.values[i]; - Object.keys(additionalChanges_1).forEach(function (keyPath) { - if (hasOwn(requestedValue_1, keyPath)) { - requestedValue_1[keyPath] = additionalChanges_1[keyPath]; - } - else { - setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); - } - }); - } - } - return ctx; - }); - return downTable.mutate(req).then(function (_a) { - var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; - for (var i = 0; i < keys.length; ++i) { - var primKey = results ? results[i] : keys[i]; - var ctx = contexts[i]; - if (primKey == null) { - ctx.onerror && ctx.onerror(failures[i]); - } - else { - ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? - req.values[i] : - primKey - ); - } - } - return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; - }).catch(function (error) { - contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); - return Promise.reject(error); - }); - }); - } - function deleteRange(req) { - return deleteNextChunk(req.trans, req.range, 10000); - } - function deleteNextChunk(trans, range, limit) { - return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) - .then(function (_a) { - var result = _a.result; - return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { - if (res.numFailures > 0) - return Promise.reject(res.failures[0]); - if (result.length < limit) { - return { failures: [], numFailures: 0, lastResult: undefined }; - } - else { - return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); - } - }); - }); - } - } }); - return tableMiddleware; - } })); } - }; - function getExistingValues(table, req, effectiveKeys) { - return req.type === "add" - ? Promise.resolve([]) - : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); - } - - function getFromTransactionCache(keys, cache, clone) { - try { - if (!cache) - return null; - if (cache.keys.length < keys.length) - return null; - var result = []; - for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { - if (cmp(cache.keys[i], keys[j]) !== 0) - continue; - result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); - ++j; - } - return result.length === keys.length ? result : null; - } - catch (_a) { - return null; - } - } - var cacheExistingValuesMiddleware = { - stack: "dbcore", - level: -1, - create: function (core) { - return { - table: function (tableName) { - var table = core.table(tableName); - return __assign(__assign({}, table), { getMany: function (req) { - if (!req.cache) { - return table.getMany(req); - } - var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); - if (cachedResult) { - return DexiePromise.resolve(cachedResult); - } - return table.getMany(req).then(function (res) { - req.trans["_cache"] = { - keys: req.keys, - values: req.cache === "clone" ? deepClone(res) : res, - }; - return res; - }); - }, mutate: function (req) { - if (req.type !== "add") - req.trans["_cache"] = null; - return table.mutate(req); - } }); - }, - }; - }, - }; - - function isCachableContext(ctx, table) { - return (ctx.trans.mode === 'readonly' && - !!ctx.subscr && - !ctx.trans.explicit && - ctx.trans.db._options.cache !== 'disabled' && - !table.schema.primaryKey.outbound); - } - - function isCachableRequest(type, req) { - switch (type) { - case 'query': - return req.values && !req.unique; - case 'get': - return false; - case 'getMany': - return false; - case 'count': - return false; - case 'openCursor': - return false; - } - } - - var observabilityMiddleware = { - stack: "dbcore", - level: 0, - name: "Observability", - create: function (core) { - var dbName = core.schema.name; - var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); - return __assign(__assign({}, core), { transaction: function (stores, mode, options) { - if (PSD.subscr && mode !== 'readonly') { - throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); - } - return core.transaction(stores, mode, options); - }, table: function (tableName) { - var table = core.table(tableName); - var schema = table.schema; - var primaryKey = schema.primaryKey, indexes = schema.indexes; - var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; - var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function (index) { return index.compound && index.keyPath.includes(primaryKey.keyPath); }); - var tableClone = __assign(__assign({}, table), { mutate: function (req) { - var trans = req.trans; - var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); - var getRangeSet = function (indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return (mutatedParts[part] || - (mutatedParts[part] = new RangeSet())); - }; - var pkRangeSet = getRangeSet(""); - var delsRangeSet = getRangeSet(":dels"); - var type = req.type; - var _a = req.type === "deleteRange" - ? [req.range] - : req.type === "delete" - ? [req.keys] - : req.values.length < 50 - ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values] - : [], keys = _a[0], newObjs = _a[1]; - var oldCache = req.trans["_cache"]; - if (isArray(keys)) { - pkRangeSet.addKeys(keys); - var oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null; - if (!oldObjs) { - delsRangeSet.addKeys(keys); - } - if (oldObjs || newObjs) { - trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); - } - } - else if (keys) { - var range = { from: keys.lower, to: keys.upper }; - delsRangeSet.add(range); - pkRangeSet.add(range); - } - else { - pkRangeSet.add(FULL_RANGE); - delsRangeSet.add(FULL_RANGE); - schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); - } - return table.mutate(req).then(function (res) { - if (keys && (req.type === 'add' || req.type === 'put')) { - pkRangeSet.addKeys(res.results); - if (indexesWithAutoIncPK) { - indexesWithAutoIncPK.forEach(function (idx) { - var idxVals = req.values.map(function (v) { return idx.extractKey(v); }); - var pkPos = idx.keyPath.findIndex(function (prop) { return prop === primaryKey.keyPath; }); - res.results.forEach(function (pk) { return idxVals[pkPos] = pk; }); - getRangeSet(idx.name).addKeys(idxVals); - }); - } - } - trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); - return res; - }); - } }); - var getRange = function (_a) { - var _b, _c; - var _d = _a.query, index = _d.index, range = _d.range; - return [ - index, - new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), - ]; - }; - var readSubscribers = { - get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, - getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, - count: getRange, - query: getRange, - openCursor: getRange, - }; - keys(readSubscribers).forEach(function (method) { - tableClone[method] = function (req) { - var subscr = PSD.subscr; - var isLiveQuery = !!subscr; - var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); - var obsSet = cachable - ? req.obsSet = {} - : subscr; - if (isLiveQuery) { - var getRangeSet = function (indexName) { - var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); - return (obsSet[part] || - (obsSet[part] = new RangeSet())); - }; - var pkRangeSet_1 = getRangeSet(""); - var delsRangeSet_1 = getRangeSet(":dels"); - var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; - if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) { - delsRangeSet_1.add(queriedRanges); - } - else { - getRangeSet(queriedIndex.name || "").add(queriedRanges); - } - if (!queriedIndex.isPrimaryKey) { - if (method === "count") { - delsRangeSet_1.add(FULL_RANGE); - } - else { - var keysPromise_1 = method === "query" && - outbound && - req.values && - table.query(__assign(__assign({}, req), { values: false })); - return table[method].apply(this, arguments).then(function (res) { - if (method === "query") { - if (outbound && req.values) { - return keysPromise_1.then(function (_a) { - var resultingKeys = _a.result; - pkRangeSet_1.addKeys(resultingKeys); - return res; - }); - } - var pKeys = req.values - ? res.result.map(extractKey) - : res.result; - if (req.values) { - pkRangeSet_1.addKeys(pKeys); - } - else { - delsRangeSet_1.addKeys(pKeys); - } - } - else if (method === "openCursor") { - var cursor_1 = res; - var wantValues_1 = req.values; - return (cursor_1 && - Object.create(cursor_1, { - key: { - get: function () { - delsRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.key; - }, - }, - primaryKey: { - get: function () { - var pkey = cursor_1.primaryKey; - delsRangeSet_1.addKey(pkey); - return pkey; - }, - }, - value: { - get: function () { - wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); - return cursor_1.value; - }, - }, - })); - } - return res; - }); - } - } - } - return table[method].apply(this, arguments); - }; - }); - return tableClone; - } }); - }, - }; - function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { - function addAffectedIndex(ix) { - var rangeSet = getRangeSet(ix.name || ""); - function extractKey(obj) { - return obj != null ? ix.extractKey(obj) : null; - } - var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) - ? key.forEach(function (key) { return rangeSet.addKey(key); }) - : rangeSet.addKey(key); }; - (oldObjs || newObjs).forEach(function (_, i) { - var oldKey = oldObjs && extractKey(oldObjs[i]); - var newKey = newObjs && extractKey(newObjs[i]); - if (cmp(oldKey, newKey) !== 0) { - if (oldKey != null) - addKeyOrKeys(oldKey); - if (newKey != null) - addKeyOrKeys(newKey); - } - }); - } - schema.indexes.forEach(addAffectedIndex); - } - - function adjustOptimisticFromFailures(tblCache, req, res) { - if (res.numFailures === 0) - return req; - if (req.type === 'deleteRange') { - return null; - } - var numBulkOps = req.keys - ? req.keys.length - : 'values' in req && req.values - ? req.values.length - : 1; - if (res.numFailures === numBulkOps) { - return null; - } - var clone = __assign({}, req); - if (isArray(clone.keys)) { - clone.keys = clone.keys.filter(function (_, i) { return !(i in res.failures); }); - } - if ('values' in clone && isArray(clone.values)) { - clone.values = clone.values.filter(function (_, i) { return !(i in res.failures); }); - } - return clone; - } - - function isAboveLower(key, range) { - return range.lower === undefined - ? true - : range.lowerOpen - ? cmp(key, range.lower) > 0 - : cmp(key, range.lower) >= 0; - } - function isBelowUpper(key, range) { - return range.upper === undefined - ? true - : range.upperOpen - ? cmp(key, range.upper) < 0 - : cmp(key, range.upper) <= 0; - } - function isWithinRange(key, range) { - return isAboveLower(key, range) && isBelowUpper(key, range); - } - - function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { - if (!ops || ops.length === 0) - return result; - var index = req.query.index; - var multiEntry = index.multiEntry; - var queryRange = req.query.range; - var primaryKey = table.schema.primaryKey; - var extractPrimKey = primaryKey.extractKey; - var extractIndex = index.extractKey; - var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; - var finalResult = ops.reduce(function (result, op) { - var modifedResult = result; - var includedValues = op.type === 'add' || op.type === 'put' - ? op.values.filter(function (v) { - var key = extractIndex(v); - return multiEntry && isArray(key) - ? key.some(function (k) { return isWithinRange(k, queryRange); }) - : isWithinRange(key, queryRange); - }).map(function (v) { - v = deepClone(v); - if (immutable) - Object.freeze(v); - return v; - }) - : []; - switch (op.type) { - case 'add': - modifedResult = result.concat(req.values - ? includedValues - : includedValues.map(function (v) { return extractPrimKey(v); })); - break; - case 'put': - var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); })); - modifedResult = result - .filter(function (item) { - var key = req.values ? extractPrimKey(item) : item; - return !rangesOverlap(new RangeSet(key), keySet_1); - }) - .concat(req.values - ? includedValues - : includedValues.map(function (v) { return extractPrimKey(v); })); - break; - case 'delete': - var keysToDelete_1 = new RangeSet().addKeys(op.keys); - modifedResult = result.filter(function (item) { - var key = req.values ? extractPrimKey(item) : item; - return !rangesOverlap(new RangeSet(key), keysToDelete_1); - }); - break; - case 'deleteRange': - var range_1 = op.range; - modifedResult = result.filter(function (item) { return !isWithinRange(extractPrimKey(item), range_1); }); - break; - } - return modifedResult; - }, result); - if (finalResult === result) - return result; - finalResult.sort(function (a, b) { - return cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) || - cmp(extractPrimKey(a), extractPrimKey(b)); - }); - if (req.limit && req.limit < Infinity) { - if (finalResult.length > req.limit) { - finalResult.length = req.limit; - } - else if (result.length === req.limit && finalResult.length < req.limit) { - cacheEntry.dirty = true; - } - } - return immutable ? Object.freeze(finalResult) : finalResult; - } - - function areRangesEqual(r1, r2) { - return (cmp(r1.lower, r2.lower) === 0 && - cmp(r1.upper, r2.upper) === 0 && - !!r1.lowerOpen === !!r2.lowerOpen && - !!r1.upperOpen === !!r2.upperOpen); - } - - function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { - if (lower1 === undefined) - return lower2 !== undefined ? -1 : 0; - if (lower2 === undefined) - return 1; - var c = cmp(lower1, lower2); - if (c === 0) { - if (lowerOpen1 && lowerOpen2) - return 0; - if (lowerOpen1) - return 1; - if (lowerOpen2) - return -1; - } - return c; - } - function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { - if (upper1 === undefined) - return upper2 !== undefined ? 1 : 0; - if (upper2 === undefined) - return -1; - var c = cmp(upper1, upper2); - if (c === 0) { - if (upperOpen1 && upperOpen2) - return 0; - if (upperOpen1) - return -1; - if (upperOpen2) - return 1; - } - return c; - } - function isSuperRange(r1, r2) { - return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && - compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0); - } - - function findCompatibleQuery(dbName, tableName, type, req) { - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return []; - var queries = tblCache.queries[type]; - if (!queries) - return [null, false, tblCache, null]; - var indexName = req.query ? req.query.index.name : null; - var entries = queries[indexName || '']; - if (!entries) - return [null, false, tblCache, null]; - switch (type) { - case 'query': - var equalEntry = entries.find(function (entry) { - return entry.req.limit === req.limit && - entry.req.values === req.values && - areRangesEqual(entry.req.query.range, req.query.range); - }); - if (equalEntry) - return [ - equalEntry, - true, - tblCache, - entries, - ]; - var superEntry = entries.find(function (entry) { - var limit = 'limit' in entry.req ? entry.req.limit : Infinity; - return (limit >= req.limit && - (req.values ? entry.req.values : true) && - isSuperRange(entry.req.query.range, req.query.range)); - }); - return [superEntry, false, tblCache, entries]; - case 'count': - var countQuery = entries.find(function (entry) { - return areRangesEqual(entry.req.query.range, req.query.range); - }); - return [countQuery, !!countQuery, tblCache, entries]; - } - } - - function subscribeToCacheEntry(cacheEntry, container, requery, signal) { - cacheEntry.subscribers.add(requery); - signal.addEventListener("abort", function () { - cacheEntry.subscribers.delete(requery); - if (cacheEntry.subscribers.size === 0) { - enqueForDeletion(cacheEntry, container); - } - }); - } - function enqueForDeletion(cacheEntry, container) { - setTimeout(function () { - if (cacheEntry.subscribers.size === 0) { - delArrayItem(container, cacheEntry); - } - }, 3000); - } - - var cacheMiddleware = { - stack: 'dbcore', - level: 0, - name: 'Cache', - create: function (core) { - var dbName = core.schema.name; - var coreMW = __assign(__assign({}, core), { transaction: function (stores, mode, options) { - var idbtrans = core.transaction(stores, mode, options); - if (mode === 'readwrite') { - var ac_1 = new AbortController(); - var signal = ac_1.signal; - var endTransaction = function (wasCommitted) { return function () { - ac_1.abort(); - if (mode === 'readwrite') { - var affectedSubscribers_1 = new Set(); - for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { - var storeName = stores_1[_i]; - var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; - if (tblCache) { - var table = core.table(storeName); - var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; }); - if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) { - for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) { - var entries = _b[_a]; - for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { - var entry = _d[_c]; - if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - } - } - } - else if (ops.length > 0) { - tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; }); - for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) { - var entries = _f[_e]; - for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) { - var entry = _h[_g]; - if (entry.res != null && - idbtrans.mutatedParts - ) { - if (wasCommitted && !entry.dirty) { - var freezeResults = Object.isFrozen(entry.res); - var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); - if (entry.dirty) { - delArrayItem(entries, entry); - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - else if (modRes !== entry.res) { - entry.res = modRes; - entry.promise = DexiePromise.resolve({ result: modRes }); - } - } - else { - if (entry.dirty) { - delArrayItem(entries, entry); - } - entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); - } - } - } - } - } - } - } - affectedSubscribers_1.forEach(function (requery) { return requery(); }); - } - }; }; - idbtrans.addEventListener('abort', endTransaction(false), { - signal: signal, - }); - idbtrans.addEventListener('error', endTransaction(false), { - signal: signal, - }); - idbtrans.addEventListener('complete', endTransaction(true), { - signal: signal, - }); - } - return idbtrans; - }, table: function (tableName) { - var downTable = core.table(tableName); - var primKey = downTable.schema.primaryKey; - var tableMW = __assign(__assign({}, downTable), { mutate: function (req) { - var trans = PSD.trans; - if (primKey.outbound || - trans.db._options.cache === 'disabled' || - trans.explicit - ) { - return downTable.mutate(req); - } - var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; - if (!tblCache) - return downTable.mutate(req); - var promise = downTable.mutate(req); - if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function (key) { return key == null; }))) { - promise.then(function (res) { - var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function (value, i) { - var _a; - var valueWithKey = ((_a = primKey.keyPath) === null || _a === void 0 ? void 0 : _a.includes('.')) - ? deepClone(value) - : __assign({}, value); - setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); - return valueWithKey; - }) }); - var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res); - tblCache.optimisticOps.push(adjustedReq); - queueMicrotask(function () { return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); }); - }); - } - else { - tblCache.optimisticOps.push(req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - promise.then(function (res) { - if (res.numFailures > 0) { - delArrayItem(tblCache.optimisticOps, req); - var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res); - if (adjustedReq) { - tblCache.optimisticOps.push(adjustedReq); - } - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - } - }); - promise.catch(function () { - delArrayItem(tblCache.optimisticOps, req); - req.mutatedParts && signalSubscribersLazily(req.mutatedParts); - }); - } - return promise; - }, query: function (req) { - var _a; - if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) - return downTable.query(req); - var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable'; - var _b = PSD, requery = _b.requery, signal = _b.signal; - var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3]; - if (cacheEntry && exactMatch) { - cacheEntry.obsSet = req.obsSet; - } - else { - var promise = downTable.query(req).then(function (res) { - var result = res.result; - if (cacheEntry) - cacheEntry.res = result; - if (freezeResults) { - for (var i = 0, l = result.length; i < l; ++i) { - Object.freeze(result[i]); - } - Object.freeze(result); - } - else { - res.result = deepClone(result); - } - return res; - }).catch(function (error) { - if (container && cacheEntry) - delArrayItem(container, cacheEntry); - return Promise.reject(error); - }); - cacheEntry = { - obsSet: req.obsSet, - promise: promise, - subscribers: new Set(), - type: 'query', - req: req, - dirty: false, - }; - if (container) { - container.push(cacheEntry); - } - else { - container = [cacheEntry]; - if (!tblCache) { - tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { - queries: { - query: {}, - count: {}, - }, - objs: new Map(), - optimisticOps: [], - unsignaledParts: {} - }; - } - tblCache.queries.query[req.query.index.name || ''] = container; - } - } - subscribeToCacheEntry(cacheEntry, container, requery, signal); - return cacheEntry.promise.then(function (res) { - return { - result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults), - }; - }); - } }); - return tableMW; - } }); - return coreMW; - }, - }; - - function vipify(target, vipDb) { - return new Proxy(target, { - get: function (target, prop, receiver) { - if (prop === 'db') - return vipDb; - return Reflect.get(target, prop, receiver); - } - }); - } - - var Dexie$1 = (function () { - function Dexie(name, options) { - var _this = this; - this._middlewares = {}; - this.verno = 0; - var deps = Dexie.dependencies; - this._options = options = __assign({ - addons: Dexie.addons, autoOpen: true, - indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange, cache: 'cloned' }, options); - this._deps = { - indexedDB: options.indexedDB, - IDBKeyRange: options.IDBKeyRange - }; - var addons = options.addons; - this._dbSchema = {}; - this._versions = []; - this._storeNames = []; - this._allTables = {}; - this.idbdb = null; - this._novip = this; - var state = { - dbOpenError: null, - isBeingOpened: false, - onReadyBeingFired: null, - openComplete: false, - dbReadyResolve: nop, - dbReadyPromise: null, - cancelOpen: nop, - openCanceller: null, - autoSchema: true, - PR1398_maxLoop: 3, - autoOpen: options.autoOpen, - }; - state.dbReadyPromise = new DexiePromise(function (resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function (_, reject) { - state.cancelOpen = reject; - }); - this._state = state; - this.name = name; - this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); - this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { - return function (subscriber, bSticky) { - Dexie.vip(function () { - var state = _this._state; - if (state.openComplete) { - if (!state.dbOpenError) - DexiePromise.resolve().then(subscriber); - if (bSticky) - subscribe(subscriber); - } - else if (state.onReadyBeingFired) { - state.onReadyBeingFired.push(subscriber); - if (bSticky) - subscribe(subscriber); - } - else { - subscribe(subscriber); - var db_1 = _this; - if (!bSticky) - subscribe(function unsubscribe() { - db_1.on.ready.unsubscribe(subscriber); - db_1.on.ready.unsubscribe(unsubscribe); - }); - } - }); - }; - }); - this.Collection = createCollectionConstructor(this); - this.Table = createTableConstructor(this); - this.Transaction = createTransactionConstructor(this); - this.Version = createVersionConstructor(this); - this.WhereClause = createWhereClauseConstructor(this); - this.on("versionchange", function (ev) { - if (ev.newVersion > 0) - console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); - else - console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); - _this.close({ disableAutoOpen: false }); - }); - this.on("blocked", function (ev) { - if (!ev.newVersion || ev.newVersion < ev.oldVersion) - console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); - else - console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); - }); - this._maxKey = getMaxKey(options.IDBKeyRange); - this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); }; - this._fireOnBlocked = function (ev) { - _this.on("blocked").fire(ev); - connections - .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) - .map(function (c) { return c.on("versionchange").fire(ev); }); - }; - this.use(cacheExistingValuesMiddleware); - this.use(cacheMiddleware); - this.use(observabilityMiddleware); - this.use(virtualIndexMiddleware); - this.use(hooksMiddleware); - var vipDB = new Proxy(this, { - get: function (_, prop, receiver) { - if (prop === '_vip') - return true; - if (prop === 'table') - return function (tableName) { return vipify(_this.table(tableName), vipDB); }; - var rv = Reflect.get(_, prop, receiver); - if (rv instanceof Table) - return vipify(rv, vipDB); - if (prop === 'tables') - return rv.map(function (t) { return vipify(t, vipDB); }); - if (prop === '_createTransaction') - return function () { - var tx = rv.apply(this, arguments); - return vipify(tx, vipDB); - }; - return rv; - } - }); - this.vip = vipDB; - addons.forEach(function (addon) { return addon(_this); }); - } - Dexie.prototype.version = function (versionNumber) { - if (isNaN(versionNumber) || versionNumber < 0.1) - throw new exceptions.Type("Given version is not a positive number"); - versionNumber = Math.round(versionNumber * 10) / 10; - if (this.idbdb || this._state.isBeingOpened) - throw new exceptions.Schema("Cannot add version when database is open"); - this.verno = Math.max(this.verno, versionNumber); - var versions = this._versions; - var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; - if (versionInstance) - return versionInstance; - versionInstance = new this.Version(versionNumber); - versions.push(versionInstance); - versions.sort(lowerVersionFirst); - versionInstance.stores({}); - this._state.autoSchema = false; - return versionInstance; - }; - Dexie.prototype._whenReady = function (fn) { - var _this = this; - return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { - if (_this._state.openComplete) { - return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); - } - if (!_this._state.isBeingOpened) { - if (!_this._state.autoOpen) { - reject(new exceptions.DatabaseClosed()); - return; - } - _this.open().catch(nop); - } - _this._state.dbReadyPromise.then(resolve, reject); - }).then(fn); - }; - Dexie.prototype.use = function (_a) { - var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; - if (name) - this.unuse({ stack: stack, name: name }); - var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); - middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); - middlewares.sort(function (a, b) { return a.level - b.level; }); - return this; - }; - Dexie.prototype.unuse = function (_a) { - var stack = _a.stack, name = _a.name, create = _a.create; - if (stack && this._middlewares[stack]) { - this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { - return create ? mw.create !== create : - name ? mw.name !== name : - false; - }); - } - return this; - }; - Dexie.prototype.open = function () { - var _this = this; - return usePSD(globalPSD, - function () { return dexieOpen(_this); }); - }; - Dexie.prototype._close = function () { - var state = this._state; - var idx = connections.indexOf(this); - if (idx >= 0) - connections.splice(idx, 1); - if (this.idbdb) { - try { - this.idbdb.close(); - } - catch (e) { } - this.idbdb = null; - } - if (!state.isBeingOpened) { - state.dbReadyPromise = new DexiePromise(function (resolve) { - state.dbReadyResolve = resolve; - }); - state.openCanceller = new DexiePromise(function (_, reject) { - state.cancelOpen = reject; - }); - } - }; - Dexie.prototype.close = function (_a) { - var _b = _a === void 0 ? { disableAutoOpen: true } : _a, disableAutoOpen = _b.disableAutoOpen; - var state = this._state; - if (disableAutoOpen) { - if (state.isBeingOpened) { - state.cancelOpen(new exceptions.DatabaseClosed()); - } - this._close(); - state.autoOpen = false; - state.dbOpenError = new exceptions.DatabaseClosed(); - } - else { - this._close(); - state.autoOpen = this._options.autoOpen || - state.isBeingOpened; - state.openComplete = false; - state.dbOpenError = null; - } - }; - Dexie.prototype.delete = function (closeOptions) { - var _this = this; - if (closeOptions === void 0) { closeOptions = { disableAutoOpen: true }; } - var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== 'object'; - var state = this._state; - return new DexiePromise(function (resolve, reject) { - var doDelete = function () { - _this.close(closeOptions); - var req = _this._deps.indexedDB.deleteDatabase(_this.name); - req.onsuccess = wrap(function () { - _onDatabaseDeleted(_this._deps, _this.name); - resolve(); - }); - req.onerror = eventRejectHandler(reject); - req.onblocked = _this._fireOnBlocked; - }; - if (hasInvalidArguments) - throw new exceptions.InvalidArgument("Invalid closeOptions argument to db.delete()"); - if (state.isBeingOpened) { - state.dbReadyPromise.then(doDelete); - } - else { - doDelete(); - } - }); - }; - Dexie.prototype.backendDB = function () { - return this.idbdb; - }; - Dexie.prototype.isOpen = function () { - return this.idbdb !== null; - }; - Dexie.prototype.hasBeenClosed = function () { - var dbOpenError = this._state.dbOpenError; - return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); - }; - Dexie.prototype.hasFailed = function () { - return this._state.dbOpenError !== null; - }; - Dexie.prototype.dynamicallyOpened = function () { - return this._state.autoSchema; - }; - Object.defineProperty(Dexie.prototype, "tables", { - get: function () { - var _this = this; - return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); - }, - enumerable: false, - configurable: true - }); - Dexie.prototype.transaction = function () { - var args = extractTransactionArgs.apply(this, arguments); - return this._transaction.apply(this, args); - }; - Dexie.prototype._transaction = function (mode, tables, scopeFunc) { - var _this = this; - var parentTransaction = PSD.trans; - if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) - parentTransaction = null; - var onlyIfCompatible = mode.indexOf('?') !== -1; - mode = mode.replace('!', '').replace('?', ''); - var idbMode, storeNames; - try { - storeNames = tables.map(function (table) { - var storeName = table instanceof _this.Table ? table.name : table; - if (typeof storeName !== 'string') - throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); - return storeName; - }); - if (mode == "r" || mode === READONLY) - idbMode = READONLY; - else if (mode == "rw" || mode == READWRITE) - idbMode = READWRITE; - else - throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); - if (parentTransaction) { - if (parentTransaction.mode === READONLY && idbMode === READWRITE) { - if (onlyIfCompatible) { - parentTransaction = null; - } - else - throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); - } - if (parentTransaction) { - storeNames.forEach(function (storeName) { - if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { - if (onlyIfCompatible) { - parentTransaction = null; - } - else - throw new exceptions.SubTransaction("Table " + storeName + - " not included in parent transaction."); - } - }); - } - if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { - parentTransaction = null; - } - } - } - catch (e) { - return parentTransaction ? - parentTransaction._promise(null, function (_, reject) { reject(e); }) : - rejection(e); - } - var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); - return (parentTransaction ? - parentTransaction._promise(idbMode, enterTransaction, "lock") : - PSD.trans ? - usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : - this._whenReady(enterTransaction)); - }; - Dexie.prototype.table = function (tableName) { - if (!hasOwn(this._allTables, tableName)) { - throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); - } - return this._allTables[tableName]; - }; - return Dexie; - }()); - - var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol - ? Symbol.observable - : "@@observable"; - var Observable = (function () { - function Observable(subscribe) { - this._subscribe = subscribe; - } - Observable.prototype.subscribe = function (x, error, complete) { - return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); - }; - Observable.prototype[symbolObservable] = function () { - return this; - }; - return Observable; - }()); - - var domDeps; - try { - domDeps = { - indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, - IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange - }; - } - catch (e) { - domDeps = { indexedDB: null, IDBKeyRange: null }; - } - - function liveQuery(querier) { - var hasValue = false; - var currentValue; - var observable = new Observable(function (observer) { - var scopeFuncIsAsync = isAsyncFunction(querier); - function execute(ctx) { - var wasRootExec = beginMicroTickScope(); - try { - if (scopeFuncIsAsync) { - incrementExpectedAwaits(); - } - var rv = newScope(querier, ctx); - if (scopeFuncIsAsync) { - rv = rv.finally(decrementExpectedAwaits); - } - return rv; - } - finally { - wasRootExec && endMicroTickScope(); - } - } - var closed = false; - var abortController; - var accumMuts = {}; - var currentObs = {}; - var subscription = { - get closed() { - return closed; - }, - unsubscribe: function () { - if (closed) - return; - closed = true; - if (abortController) - abortController.abort(); - if (startedListening) - globalEvents.storagemutated.unsubscribe(mutationListener); - }, - }; - observer.start && observer.start(subscription); - var startedListening = false; - var doQuery = function () { return execInGlobalContext(_doQuery); }; - function shouldNotify() { - return obsSetsOverlap(currentObs, accumMuts); - } - var mutationListener = function (parts) { - extendObservabilitySet(accumMuts, parts); - if (shouldNotify()) { - doQuery(); - } - }; - var _doQuery = function () { - if (closed || - !domDeps.indexedDB) - { - return; - } - accumMuts = {}; - var subscr = {}; - if (abortController) - abortController.abort(); - abortController = new AbortController(); - var ctx = { - subscr: subscr, - signal: abortController.signal, - requery: doQuery, - querier: querier, - trans: null - }; - var ret = execute(ctx); - Promise.resolve(ret).then(function (result) { - hasValue = true; - currentValue = result; - if (closed || ctx.signal.aborted) { - return; - } - accumMuts = {}; - currentObs = subscr; - if (!objectIsEmpty(currentObs) && !startedListening) { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); - startedListening = true; - } - execInGlobalContext(function () { return !closed && observer.next && observer.next(result); }); - }, function (err) { - hasValue = false; - if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) { - if (!closed) - execInGlobalContext(function () { - if (closed) - return; - observer.error && observer.error(err); - }); - } - }); - }; - setTimeout(doQuery, 0); - return subscription; - }); - observable.hasValue = function () { return hasValue; }; - observable.getValue = function () { return currentValue; }; - return observable; - } - - var Dexie = Dexie$1; - props(Dexie, __assign(__assign({}, fullNameExceptions), { - delete: function (databaseName) { - var db = new Dexie(databaseName, { addons: [] }); - return db.delete(); - }, - exists: function (name) { - return new Dexie(name, { addons: [] }).open().then(function (db) { - db.close(); - return true; - }).catch('NoSuchDatabaseError', function () { return false; }); - }, - getDatabaseNames: function (cb) { - try { - return getDatabaseNames(Dexie.dependencies).then(cb); - } - catch (_a) { - return rejection(new exceptions.MissingAPI()); - } - }, - defineClass: function () { - function Class(content) { - extend(this, content); - } - return Class; - }, ignoreTransaction: function (scopeFunc) { - return PSD.trans ? - usePSD(PSD.transless, scopeFunc) : - scopeFunc(); - }, vip: vip, async: function (generatorFn) { - return function () { - try { - var rv = awaitIterator(generatorFn.apply(this, arguments)); - if (!rv || typeof rv.then !== 'function') - return DexiePromise.resolve(rv); - return rv; - } - catch (e) { - return rejection(e); - } - }; - }, spawn: function (generatorFn, args, thiz) { - try { - var rv = awaitIterator(generatorFn.apply(thiz, args || [])); - if (!rv || typeof rv.then !== 'function') - return DexiePromise.resolve(rv); - return rv; - } - catch (e) { - return rejection(e); - } - }, - currentTransaction: { - get: function () { return PSD.trans || null; } - }, waitFor: function (promiseOrFunction, optionalTimeout) { - var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? - Dexie.ignoreTransaction(promiseOrFunction) : - promiseOrFunction) - .timeout(optionalTimeout || 60000); - return PSD.trans ? - PSD.trans.waitFor(promise) : - promise; - }, - Promise: DexiePromise, - debug: { - get: function () { return debug; }, - set: function (value) { - setDebug(value); - } - }, - derive: derive, extend: extend, props: props, override: override, - Events: Events, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, - getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, - minKey: minKey, - addons: [], - connections: connections, - errnames: errnames, - dependencies: domDeps, cache: cache, - semVer: DEXIE_VERSION, version: DEXIE_VERSION.split('.') - .map(function (n) { return parseInt(n); }) - .reduce(function (p, c, i) { return p + (c / Math.pow(10, i * 2)); }) })); - Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); - - if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { - if (!propagatingLocally) { - var event_1; - event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { - detail: updatedParts - }); - propagatingLocally = true; - dispatchEvent(event_1); - propagatingLocally = false; - } - }); - addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { - var detail = _a.detail; - if (!propagatingLocally) { - propagateLocally(detail); - } - }); - } - function propagateLocally(updateParts) { - var wasMe = propagatingLocally; - try { - propagatingLocally = true; - globalEvents.storagemutated.fire(updateParts); - signalSubscribersNow(updateParts, true); - } - finally { - propagatingLocally = wasMe; - } - } - var propagatingLocally = false; - - var bc; - var createBC = function () { }; - if (typeof BroadcastChannel !== 'undefined') { - createBC = function () { - bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); - bc.onmessage = function (ev) { return ev.data && propagateLocally(ev.data); }; - }; - createBC(); - if (typeof bc.unref === 'function') { - bc.unref(); - } - globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { - if (!propagatingLocally) { - bc.postMessage(changedParts); - } - }); - } - - if (typeof addEventListener !== 'undefined') { - addEventListener('pagehide', function (event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug('Dexie: handling persisted pagehide'); - bc === null || bc === void 0 ? void 0 : bc.close(); - for (var _i = 0, connections_1 = connections; _i < connections_1.length; _i++) { - var db = connections_1[_i]; - db.close({ disableAutoOpen: false }); - } - } - }); - addEventListener('pageshow', function (event) { - if (!Dexie$1.disableBfCache && event.persisted) { - if (debug) - console.debug('Dexie: handling persisted pageshow'); - createBC(); - propagateLocally({ all: new RangeSet(-Infinity, [[]]) }); - } - }); - } - - function replacePrefix(a, b) { - return new PropModification({ replacePrefix: [a, b] }); - } - - DexiePromise.rejectionMapper = mapError; - setDebug(debug); - - var namedExports = /*#__PURE__*/Object.freeze({ - __proto__: null, - Dexie: Dexie$1, - liveQuery: liveQuery, - Entity: Entity, - cmp: cmp, - PropModSymbol: PropModSymbol, - PropModification: PropModification, - replacePrefix: replacePrefix, - 'default': Dexie$1, - RangeSet: RangeSet, - mergeRanges: mergeRanges, - rangesOverlap: rangesOverlap - }); - - __assign(Dexie$1, namedExports, { default: Dexie$1 }); - - return Dexie$1; - -})); - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNET.js": -/*!*******************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNET.js ***! - \*******************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AbortCurrentTransaction: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.AbortCurrentTransaction), -/* harmony export */ AbortTransaction: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.AbortTransaction), -/* harmony export */ AddByteArray: () => (/* reexport safe */ _dexieNETTable__WEBPACK_IMPORTED_MODULE_2__.AddByteArray), -/* harmony export */ BulkAddByteArray: () => (/* reexport safe */ _dexieNETTable__WEBPACK_IMPORTED_MODULE_2__.BulkAddByteArray), -/* harmony export */ BulkPutByteArray: () => (/* reexport safe */ _dexieNETTable__WEBPACK_IMPORTED_MODULE_2__.BulkPutByteArray), -/* harmony export */ CollectionEach: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionEach), -/* harmony export */ CollectionEachKey: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionEachKey), -/* harmony export */ CollectionEachPrimaryKey: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionEachPrimaryKey), -/* harmony export */ CollectionEachUniqueKey: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionEachUniqueKey), -/* harmony export */ CollectionFilter: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionFilter), -/* harmony export */ CollectionKeysByteArray: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionKeysByteArray), -/* harmony export */ CollectionModify: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionModify), -/* harmony export */ CollectionModifyReplacePrefix: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionModifyReplacePrefix), -/* harmony export */ CollectionPrimarykeysByteArray: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionPrimarykeysByteArray), -/* harmony export */ CollectionUntil: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.CollectionUntil), -/* harmony export */ Create: () => (/* reexport safe */ _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__.Create), -/* harmony export */ CurrentTransaction: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.CurrentTransaction), -/* harmony export */ DB: () => (/* reexport safe */ _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__.DB), -/* harmony export */ Delete: () => (/* reexport safe */ _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__.Delete), -/* harmony export */ InitStoragePersistence: () => (/* reexport safe */ _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__.InitStoragePersistence), -/* harmony export */ LiveQuery: () => (/* reexport safe */ _dexieNETLiveQuery__WEBPACK_IMPORTED_MODULE_1__.LiveQuery), -/* harmony export */ LiveQuerySubscribe: () => (/* reexport safe */ _dexieNETLiveQuery__WEBPACK_IMPORTED_MODULE_1__.LiveQuerySubscribe), -/* harmony export */ LiveQueryUnsubscribe: () => (/* reexport safe */ _dexieNETLiveQuery__WEBPACK_IMPORTED_MODULE_1__.LiveQueryUnsubscribe), -/* harmony export */ Modify: () => (/* reexport safe */ _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__.Modify), -/* harmony export */ Name: () => (/* reexport safe */ _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__.Name), -/* harmony export */ Persist: () => (/* reexport safe */ _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__.Persist), -/* harmony export */ PutByteArray: () => (/* reexport safe */ _dexieNETTable__WEBPACK_IMPORTED_MODULE_2__.PutByteArray), -/* harmony export */ ShowEstimatedQuota: () => (/* reexport safe */ _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__.ShowEstimatedQuota), -/* harmony export */ TopLevelTransaction: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.TopLevelTransaction), -/* harmony export */ TopLevelTransactionAsync: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.TopLevelTransactionAsync), -/* harmony export */ TransactioWaitFor: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.TransactioWaitFor), -/* harmony export */ Upgrade: () => (/* reexport safe */ _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__.Upgrade), -/* harmony export */ Version: () => (/* reexport safe */ _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__.Version), -/* harmony export */ iOS: () => (/* reexport safe */ _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__.iOS), -/* harmony export */ tryPersistWithoutPromtingUser: () => (/* reexport safe */ _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__.tryPersistWithoutPromtingUser) -/* harmony export */ }); -/* harmony import */ var _dexieNETBase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dexieNETBase */ "../../DexieNET/yarn/src/dexieNETBase.js"); -/* harmony import */ var _dexieNETLiveQuery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dexieNETLiveQuery */ "../../DexieNET/yarn/src/dexieNETLiveQuery.js"); -/* harmony import */ var _dexieNETTable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dexieNETTable */ "../../DexieNET/yarn/src/dexieNETTable.js"); -/* harmony import */ var _dexieNETTransactions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dexieNETTransactions */ "../../DexieNET/yarn/src/dexieNETTransactions.js"); -/* harmony import */ var _dexieNETCollection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./dexieNETCollection */ "../../DexieNET/yarn/src/dexieNETCollection.js"); -/* harmony import */ var _dexieNETPersistence__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./dexieNETPersistence */ "../../DexieNET/yarn/src/dexieNETPersistence.js"); - - - - - - - - - - - - - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETBase.js": -/*!***********************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETBase.js ***! - \***********************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Create: () => (/* binding */ Create), -/* harmony export */ DB: () => (/* binding */ DB), -/* harmony export */ Delete: () => (/* binding */ Delete), -/* harmony export */ Name: () => (/* binding */ Name), -/* harmony export */ Version: () => (/* binding */ Version) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs"); -/* -dexieNET.js - -Copyright(c) 2022 Bernhard Straub - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. - -'DexieNET' used with permission of David Fahlander -*/ - -// @ts-ignore -class DB extends dexie__WEBPACK_IMPORTED_MODULE_0__["default"] { - constructor(name) { - super(name); - } -} -function Create(name) { - let db = new DB(name); - return db; -} -function Delete(name) { - return dexie__WEBPACK_IMPORTED_MODULE_0__["default"].delete(name); -} -function Name() { - return dexie__WEBPACK_IMPORTED_MODULE_0__["default"].name; -} -function Version(db) { - return db.verno; -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETCollection.js": -/*!*****************************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETCollection.js ***! - \*****************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ CollectionEach: () => (/* binding */ CollectionEach), -/* harmony export */ CollectionEachKey: () => (/* binding */ CollectionEachKey), -/* harmony export */ CollectionEachPrimaryKey: () => (/* binding */ CollectionEachPrimaryKey), -/* harmony export */ CollectionEachUniqueKey: () => (/* binding */ CollectionEachUniqueKey), -/* harmony export */ CollectionFilter: () => (/* binding */ CollectionFilter), -/* harmony export */ CollectionKeysByteArray: () => (/* binding */ CollectionKeysByteArray), -/* harmony export */ CollectionModify: () => (/* binding */ CollectionModify), -/* harmony export */ CollectionModifyReplacePrefix: () => (/* binding */ CollectionModifyReplacePrefix), -/* harmony export */ CollectionPrimarykeysByteArray: () => (/* binding */ CollectionPrimarykeysByteArray), -/* harmony export */ CollectionUntil: () => (/* binding */ CollectionUntil), -/* harmony export */ Modify: () => (/* binding */ Modify) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs"); - -// Wrappers -async function CollectionPrimarykeysByteArray(collection) { - var buffer = await collection.primaryKeys(); - return buffer.map(x => new Uint8Array(x)); -} -async function CollectionKeysByteArray(collection) { - var buffer = await collection.keys(); - return buffer.map(x => new Uint8Array(x)); -} -function CollectionFilter(collection, dotnetRef, filterIndex) { - return collection.filter(item => dotnetRef.invokeMethod('Filter', item, filterIndex)); -} -async function Modify(collection, changes) { - let changesK = Object.fromEntries(Object.entries(changes).map(([k, v]) => [k, v === null ? undefined : v])); - return await collection.modify(changesK); -} -function CollectionUntil(collection, dotnetRef, includeStopEntry, untilIndex) { - return collection.until(item => dotnetRef.invokeMethod('Until', item, untilIndex), includeStopEntry); -} -async function CollectionEach(collection, dotnetRef) { - await collection.each(item => dotnetRef.invokeMethod('Each', item)); -} -async function CollectionEachKey(collection, dotnetRef) { - await collection.eachKey(item => dotnetRef.invokeMethod('EachKey', item)); -} -async function CollectionEachPrimaryKey(collection, dotnetRef) { - await collection.eachPrimaryKey(item => dotnetRef.invokeMethod('EachPrimaryKey', item)); -} -async function CollectionEachUniqueKey(collection, dotnetRef) { - await collection.eachUniqueKey(item => dotnetRef.invokeMethod('EachUniqueKey', item)); -} -async function CollectionModify(collection, dotnetRef) { - return await collection.modify((value, ref) => { - var newItem = dotnetRef.invokeMethod('Modify', value); - if (newItem === null) { - delete ref.value; - } - else { - ref.value = newItem; - } - }); -} -async function CollectionModifyReplacePrefix(collection, keyPath, a, b) { - return await collection.modify({ [keyPath]: (0,dexie__WEBPACK_IMPORTED_MODULE_0__.replacePrefix)(a, b) }); -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETLiveQuery.js": -/*!****************************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETLiveQuery.js ***! - \****************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ LiveQuery: () => (/* binding */ LiveQuery), -/* harmony export */ LiveQuerySubscribe: () => (/* binding */ LiveQuerySubscribe), -/* harmony export */ LiveQueryUnsubscribe: () => (/* binding */ LiveQueryUnsubscribe) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs"); - -const liveQueryObservables = {}; -const liveQuerySubscription = {}; -// LiveQuery -function LiveQuery(dotnetRef, id) { - const query = (0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => { dotnetRef.invokeMethod('LiveQueryCallback'); }); - liveQueryObservables[id] = query; -} -function LiveQuerySubscribe(id) { - if (id in liveQueryObservables) { - let query = liveQueryObservables[id]; - let subscription = query.subscribe(); - liveQuerySubscription[id] = subscription; - } -} -function LiveQueryUnsubscribe(id) { - if (id in liveQuerySubscription) { - let subscription = liveQuerySubscription[id]; - subscription.unsubscribe(); - delete liveQuerySubscription[id]; - } -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETPersistence.js": -/*!******************************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETPersistence.js ***! - \******************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InitStoragePersistence: () => (/* binding */ InitStoragePersistence), -/* harmony export */ Persist: () => (/* binding */ Persist), -/* harmony export */ ShowEstimatedQuota: () => (/* binding */ ShowEstimatedQuota), -/* harmony export */ iOS: () => (/* binding */ iOS), -/* harmony export */ tryPersistWithoutPromtingUser: () => (/* binding */ tryPersistWithoutPromtingUser) -/* harmony export */ }); -// based on https://dexie.org/docs/StorageManager -async function InitStoragePersistence() { - const persist = await tryPersistWithoutPromtingUser(); - switch (persist) { - case "never": - return 0; - case "persisted": - return 1; - case "prompt": - return 2; - default: - return -1; - } -} -/** Tries to convert to persisted storage. - @returns {Promise} Promise resolved with true if successfully - persisted the storage, false if not, and undefined if the API is not present. -*/ -async function Persist() { - return await navigator.storage && navigator.storage.persist ? - navigator.storage.persist() : - false; -} -/** Queries available disk quota. - @see https://developer.mozilla.org/en-US/docs/Web/API/StorageEstimate - @returns {Promise<{quota: number, usage: number}>} Promise resolved with - {quota: number, usage: number} or undefined. -*/ -const seUndef = { - quota: -1, - usage: -1 -}; -async function ShowEstimatedQuota() { - return await navigator.storage && navigator.storage.estimate ? - navigator.storage.estimate() : - seUndef; -} -/** Tries to persist storage without ever prompting user. - @returns {Promise} - "never" In case persisting is not ever possible. Caller don't bother - asking user for permission. - "prompt" In case persisting would be possible if prompting user first. - "persisted" In case this call successfully silently persisted the storage, - or if it was already persisted. -*/ -async function tryPersistWithoutPromtingUser() { - if (!navigator.storage || !navigator.storage.persisted) { - return "never"; - } - let persisted = await navigator.storage.persisted(); - if (persisted) { - return "persisted"; - } - // the experimental permission API on iOS doesn't work with "persistent-storage" yet - if (iOS() || !navigator.permissions || !navigator.permissions.query) { - return "prompt"; // It MAY be successful to prompt. Don't know. - } - const permission = await navigator.permissions.query({ - name: "persistent-storage" - }); - if (permission.state === "granted") { - persisted = await navigator.storage.persist(); - if (persisted) { - return "persisted"; - } - else { - throw new Error("Failed to persist"); - } - } - if (permission.state === "prompt") { - return "prompt"; - } - return "never"; -} -function iOS() { - return [ - 'iPad Simulator', - 'iPhone Simulator', - 'iPod Simulator', - 'iPad', - 'iPhone', - 'iPod' - ].includes(navigator.platform) - // iPad on iOS 13 detection - || (navigator.userAgent.includes("Mac") && "ontouchend" in document); -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETTable.js": -/*!************************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETTable.js ***! - \************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AddByteArray: () => (/* binding */ AddByteArray), -/* harmony export */ BulkAddByteArray: () => (/* binding */ BulkAddByteArray), -/* harmony export */ BulkPutByteArray: () => (/* binding */ BulkPutByteArray), -/* harmony export */ PutByteArray: () => (/* binding */ PutByteArray) -/* harmony export */ }); -// Wrappers -async function AddByteArray(table, item, key) { - let buffer = await table.add(item, key); - return new Uint8Array(buffer); -} -async function BulkAddByteArray(table, item, keys, allKeys) { - let options = allKeys ? { allKeys: allKeys } : undefined; - let buffer = await table.bulkAdd(item, keys, options); - return allKeys == true ? buffer.map(x => new Uint8Array(x)) : new Array(new Uint8Array(buffer)); -} -async function PutByteArray(table, item, key) { - let buffer = await table.put(item, key); - return new Uint8Array(buffer); -} -async function BulkPutByteArray(table, item, keys, allKeys) { - let options = allKeys ? { allKeys: allKeys } : undefined; - let buffer = await table.bulkPut(item, keys, options); - return allKeys == true ? buffer.map(x => new Uint8Array(x)) : new Array(new Uint8Array(buffer)); -} - - -/***/ }), - -/***/ "../../DexieNET/yarn/src/dexieNETTransactions.js": -/*!*******************************************************!*\ - !*** ../../DexieNET/yarn/src/dexieNETTransactions.js ***! - \*******************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AbortCurrentTransaction: () => (/* binding */ AbortCurrentTransaction), -/* harmony export */ AbortTransaction: () => (/* binding */ AbortTransaction), -/* harmony export */ CurrentTransaction: () => (/* binding */ CurrentTransaction), -/* harmony export */ TopLevelTransaction: () => (/* binding */ TopLevelTransaction), -/* harmony export */ TopLevelTransactionAsync: () => (/* binding */ TopLevelTransactionAsync), -/* harmony export */ TransactioWaitFor: () => (/* binding */ TransactioWaitFor), -/* harmony export */ Upgrade: () => (/* binding */ Upgrade) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs"); - -// Version upgrade -function Upgrade(version, dotnetRef) { - return version.upgrade(_ => { - dotnetRef.invokeMethod('UpgradeCallback'); - }); -} -function AbortCurrentTransaction() { - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].currentTransaction?.abort(); -} -function AbortTransaction(transaction) { - transaction?.abort(); -} -function CurrentTransaction() { - return dexie__WEBPACK_IMPORTED_MODULE_0__["default"].currentTransaction; -} -// @ts-ignore -function TopLevelTransaction(db, tables, mode, dotnetRef) { - db.transaction(mode, tables, _ => dotnetRef.invokeMethod('TransactionCallback')); -} -async function TopLevelTransactionAsync(db, tables, mode, dotnetRef) { - await db.transaction(mode, tables, _ => dotnetRef.invokeMethod('TransactionCallback')); -} -async function TransactioWaitFor(dotnetRef) { - await dexie__WEBPACK_IMPORTED_MODULE_0__["default"].waitFor(async () => await dotnetRef.invokeMethodAsync('TransactionWaitForCallback')); -} - - -/***/ }), - -/***/ "./node_modules/dexie/import-wrapper.mjs": -/*!***********************************************!*\ - !*** ./node_modules/dexie/import-wrapper.mjs ***! - \***********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Dexie: () => (/* binding */ Dexie), -/* harmony export */ Entity: () => (/* binding */ Entity), -/* harmony export */ PropModSymbol: () => (/* binding */ PropModSymbol), -/* harmony export */ PropModification: () => (/* binding */ PropModification), -/* harmony export */ RangeSet: () => (/* binding */ RangeSet), -/* harmony export */ cmp: () => (/* binding */ cmp), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), -/* harmony export */ liveQuery: () => (/* binding */ liveQuery), -/* harmony export */ mergeRanges: () => (/* binding */ mergeRanges), -/* harmony export */ rangesOverlap: () => (/* binding */ rangesOverlap), -/* harmony export */ replacePrefix: () => (/* binding */ replacePrefix) -/* harmony export */ }); -/* harmony import */ var _dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dist/dexie.js */ "./node_modules/dexie/dist/dexie.js"); -// Making the module version consumable via require - to prohibit -// multiple occurrancies of the same module in the same app -// (dual package hazard, https://nodejs.org/api/packages.html#dual-package-hazard) - -const DexieSymbol = Symbol.for("Dexie"); -const Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = _dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__); -if (_dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__.semVer !== Dexie.semVer) { - throw new Error(`Two different versions of Dexie loaded in the same app: ${_dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__.semVer} and ${Dexie.semVer}`); -} -const { liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp, Entity, PropModSymbol, PropModification, replacePrefix } = Dexie; - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Dexie); - - -/***/ }), - -/***/ "./node_modules/dexie-cloud-addon/dist/modern/dexie-cloud-addon.js": -/*!*************************************************************************!*\ - !*** ./node_modules/dexie-cloud-addon/dist/modern/dexie-cloud-addon.js ***! - \*************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ dexieCloud), -/* harmony export */ dexieCloud: () => (/* binding */ dexieCloud), -/* harmony export */ getTiedObjectId: () => (/* binding */ getTiedObjectId), -/* harmony export */ getTiedRealmId: () => (/* binding */ getTiedRealmId), -/* harmony export */ resolveText: () => (/* binding */ resolveText) -/* harmony export */ }); -/* harmony import */ var dexie__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! dexie */ "./node_modules/dexie/import-wrapper.mjs"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/firstValueFrom.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/from.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/operators/filter.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/Observable.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/BehaviorSubject.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/Subject.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/of.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/fromEvent.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/merge.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/Subscription.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/throwError.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/combineLatest.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/operators/map.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/operators/share.js"); -/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! rxjs */ "./node_modules/rxjs/dist/esm5/internal/observable/timer.js"); -/* ========================================================================== - * dexie-cloud-addom.js - * ========================================================================== - * - * Dexie addon that syncs IndexedDB with Dexie Cloud. - * - * By David Fahlander, david@dexie.org - * - * ========================================================================== - * - * Version 4.0.2, Wed Apr 10 2024 - * - * https://dexie.org - * - * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ - * - */ - - - - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function assert(b) { - if (!b) - throw new Error('Assertion Failed'); -} -const _hasOwn = {}.hasOwnProperty; -function hasOwn(obj, prop) { - return _hasOwn.call(obj, prop); -} -function setByKeyPath(obj, keyPath, value) { - if (!obj || keyPath === undefined) - return; - if ('isFrozen' in Object && Object.isFrozen(obj)) - return; - if (typeof keyPath !== 'string' && 'length' in keyPath) { - assert(typeof value !== 'string' && 'length' in value); - for (var i = 0, l = keyPath.length; i < l; ++i) { - setByKeyPath(obj, keyPath[i], value[i]); - } - } - else { - var period = keyPath.indexOf('.'); - if (period !== -1) { - var currentKeyPath = keyPath.substr(0, period); - var remainingKeyPath = keyPath.substr(period + 1); - if (remainingKeyPath === '') - if (value === undefined) { - if (Array.isArray(obj)) { - if (!isNaN(parseInt(currentKeyPath))) - obj.splice(parseInt(currentKeyPath), 1); - } - else - delete obj[currentKeyPath]; - // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - } - else - obj[currentKeyPath] = value; - else { - //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - var innerObj = obj[currentKeyPath]; - //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - if (!innerObj || !hasOwn(obj, currentKeyPath)) - innerObj = (obj[currentKeyPath] = {}); - setByKeyPath(innerObj, remainingKeyPath, value); - } - } - else { - if (value === undefined) { - if (Array.isArray(obj) && !isNaN(parseInt(keyPath))) - // @ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - obj.splice(keyPath, 1); - //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - else - delete obj[keyPath]; - //@ts-ignore: even if currentKeyPath would be numeric string and obj would be array - it works. - } - else - obj[keyPath] = value; - } - } -} -const randomString$1 = typeof self !== 'undefined' && typeof crypto !== 'undefined' ? (bytes, randomFill = crypto.getRandomValues.bind(crypto)) => { - // Web - const buf = new Uint8Array(bytes); - randomFill(buf); - return self.btoa(String.fromCharCode.apply(null, buf)); -} : typeof Buffer !== 'undefined' ? (bytes, randomFill = simpleRandomFill) => { - // Node - const buf = Buffer.alloc(bytes); - randomFill(buf); - return buf.toString("base64"); -} : () => { throw new Error("No implementation of randomString was found"); }; -function simpleRandomFill(buf) { - for (let i = 0; i < buf.length; ++i) { - buf[i] = Math.floor(Math.random() * 256); - } -} - -/** Verifies that given primary key is valid. - * The reason we narrow validity for valid keys are twofold: - * 1: Make sure to only support types that can be used as an object index in DBKeyMutationSet. - * For example, ArrayBuffer cannot be used (gives "object ArrayBuffer") but Uint8Array can be - * used (gives comma-delimited list of included bytes). - * 2: Avoid using plain numbers and Dates as keys when they are synced, as they are not globally unique. - * 3: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side. - * - * @param id - * @returns - */ -function isValidSyncableID(id) { - if (typeof id === "string") - return true; - //if (validIDTypes[toStringTag(id)]) return true; - //if (Array.isArray(id)) return id.every((part) => isValidSyncableID(part)); - if (Array.isArray(id) && id.some(key => isValidSyncableID(key)) && id.every(isValidSyncableIDPart)) - return true; - return false; -} -/** Verifies that given key part is valid. - * 1: Make sure that arrays of this types are stringified correclty and works with DBKeyMutationSet. - * For example, ArrayBuffer cannot be used (gives "object ArrayBuffer") but Uint8Array can be - * used (gives comma-delimited list of included bytes). - * 2: Since we store the key as a VARCHAR server side in current version, try not promote types that stringifies to become very long server side. -*/ -function isValidSyncableIDPart(part) { - return typeof part === "string" || typeof part === "number" || Array.isArray(part) && part.every(isValidSyncableIDPart); -} -function isValidAtID(id, idPrefix) { - return !idPrefix || (typeof id === "string" && id.startsWith(idPrefix)); -} - -function applyOperation(target, table, op) { - const tbl = target[table] || (target[table] = {}); - const keys = op.keys.map(key => typeof key === 'string' ? key : JSON.stringify(key)); - switch (op.type) { - case "insert": - // TODO: Don't treat insert and upsert the same? - case "upsert": - keys.forEach((key, idx) => { - tbl[key] = { - type: "ups", - val: op.values[idx], - }; - }); - break; - case "update": - case "modify": { - keys.forEach((key, idx) => { - const changeSpec = op.type === "update" - ? op.changeSpecs[idx] - : op.changeSpec; - const entry = tbl[key]; - if (!entry) { - tbl[key] = { - type: "upd", - mod: changeSpec, - }; - } - else { - switch (entry.type) { - case "ups": - // Adjust the existing upsert with additional updates - for (const [propPath, value] of Object.entries(changeSpec)) { - setByKeyPath(entry.val, propPath, value); - } - break; - case "del": - // No action. - break; - case "upd": - // Adjust existing update with additional updates - Object.assign(entry.mod, changeSpec); // May work for deep props as well - new keys is added later, right? Does the prop order persist along TSON and all? But it will not be 100% when combined with some server code (seach for "address.city": "Stockholm" comment) - break; - } - } - }); - break; - } - case "delete": - keys.forEach((key) => { - tbl[key] = { - type: "del", - }; - }); - break; - } - return target; -} - -function applyOperations(target, ops) { - for (const { table, muts } of ops) { - for (const mut of muts) { - applyOperation(target, table, mut); - } - } -} - -function subtractChanges(target, // Server change set -changesToSubtract // additional mutations on client during syncWithServer() -) { - var _a, _b, _c; - for (const [table, mutationSet] of Object.entries(changesToSubtract)) { - for (const [key, mut] of Object.entries(mutationSet)) { - switch (mut.type) { - case 'ups': - { - const targetMut = (_a = target[table]) === null || _a === void 0 ? void 0 : _a[key]; - if (targetMut) { - switch (targetMut.type) { - case 'ups': - delete target[table][key]; - break; - case 'del': - // Leave delete operation. - // (Don't resurrect objects unintenionally (using tx(get, put) pattern locally)) - break; - case 'upd': - delete target[table][key]; - break; - } - } - } - break; - case 'del': - (_b = target[table]) === null || _b === void 0 ? true : delete _b[key]; - break; - case 'upd': { - const targetMut = (_c = target[table]) === null || _c === void 0 ? void 0 : _c[key]; - if (targetMut) { - switch (targetMut.type) { - case 'ups': - // Adjust the server upsert with locally updated values. - for (const [propPath, value] of Object.entries(mut.mod)) { - setByKeyPath(targetMut.val, propPath, value); - } - break; - case 'del': - // Leave delete. - break; - case 'upd': - // Remove the local update props from the server update mutation. - for (const propPath of Object.keys(mut.mod)) { - delete targetMut.mod[propPath]; - } - break; - } - } - break; - } - } - } - } -} - -/** Convert a DBKeyMutationSet (which is an internal format capable of looking up changes per ID) - * ...into a DBOperationsSet (which is more optimal for performing DB operations into DB (bulkAdd() etc)) - * - * @param inSet - * @returns DBOperationsSet representing inSet - */ -function toDBOperationSet(inSet, txid = "") { - // Fictive transaction: - if (!txid) - txid = randomString$1(16); - // Convert data into a temporary map to collect mutations of same table and type - const map = {}; - for (const [table, ops] of Object.entries(inSet)) { - for (const [key, op] of Object.entries(ops)) { - const mapEntry = map[table] || (map[table] = {}); - const ops = mapEntry[op.type] || (mapEntry[op.type] = []); - ops.push(Object.assign({ key }, op)); // DBKeyMutation doesn't contain key, so we need to bring it in. - } - } - // Start computing the resulting format: - const result = []; - for (const [table, ops] of Object.entries(map)) { - const resultEntry = { - table, - muts: [], - }; - for (const [optype, muts] of Object.entries(ops)) { - switch (optype) { - case "ups": { - const op = { - type: "upsert", - keys: muts.map(mut => mut.key), - values: muts.map(mut => mut.val), - txid - }; - resultEntry.muts.push(op); - break; - } - case "upd": { - const op = { - type: "update", - keys: muts.map(mut => mut.key), - changeSpecs: muts.map(mut => mut.mod), - txid - }; - resultEntry.muts.push(op); - break; - } - case "del": { - const op = { - type: "delete", - keys: muts.map(mut => mut.key), - txid, - }; - resultEntry.muts.push(op); - break; - } - } - } - result.push(resultEntry); - } - return result; -} - -function getDbNameFromDbUrl(dbUrl) { - const url = new URL(dbUrl); - return url.pathname === "/" - ? url.hostname.split('.')[0] - : url.pathname.split('/')[1]; -} - -function isFunction(value) { - return typeof value === 'function'; -} - -function hasLift(source) { - return isFunction(source === null || source === void 0 ? void 0 : source.lift); -} -function operate(init) { - return function (source) { - if (hasLift(source)) { - return source.lift(function (liftedSource) { - try { - return init(liftedSource, this); - } - catch (err) { - this.error(err); - } - }); - } - throw new TypeError('Unable to lift unknown Observable type'); - }; -} - -var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); - -function isPromise(value) { - return isFunction(value === null || value === void 0 ? void 0 : value.then); -} - -function createErrorClass(createImpl) { - var _super = function (instance) { - Error.call(instance); - instance.stack = new Error().stack; - }; - var ctorFunc = createImpl(_super); - ctorFunc.prototype = Object.create(Error.prototype); - ctorFunc.prototype.constructor = ctorFunc; - return ctorFunc; -} - -var UnsubscriptionError = createErrorClass(function (_super) { - return function UnsubscriptionErrorImpl(errors) { - _super(this); - this.message = errors - ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') - : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - }; -}); - -function arrRemove(arr, item) { - if (arr) { - var index = arr.indexOf(item); - 0 <= index && arr.splice(index, 1); - } -} - -var Subscription = (function () { - function Subscription(initialTeardown) { - this.initialTeardown = initialTeardown; - this.closed = false; - this._parentage = null; - this._finalizers = null; - } - Subscription.prototype.unsubscribe = function () { - var e_1, _a, e_2, _b; - var errors; - if (!this.closed) { - this.closed = true; - var _parentage = this._parentage; - if (_parentage) { - this._parentage = null; - if (Array.isArray(_parentage)) { - try { - for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) { - var parent_1 = _parentage_1_1.value; - parent_1.remove(this); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1); - } - finally { if (e_1) throw e_1.error; } - } - } - else { - _parentage.remove(this); - } - } - var initialFinalizer = this.initialTeardown; - if (isFunction(initialFinalizer)) { - try { - initialFinalizer(); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? e.errors : [e]; - } - } - var _finalizers = this._finalizers; - if (_finalizers) { - this._finalizers = null; - try { - for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) { - var finalizer = _finalizers_1_1.value; - try { - execFinalizer(finalizer); - } - catch (err) { - errors = errors !== null && errors !== void 0 ? errors : []; - if (err instanceof UnsubscriptionError) { - errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)); - } - else { - errors.push(err); - } - } - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1); - } - finally { if (e_2) throw e_2.error; } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - } - }; - Subscription.prototype.add = function (teardown) { - var _a; - if (teardown && teardown !== this) { - if (this.closed) { - execFinalizer(teardown); - } - else { - if (teardown instanceof Subscription) { - if (teardown.closed || teardown._hasParent(this)) { - return; - } - teardown._addParent(this); - } - (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown); - } - } - }; - Subscription.prototype._hasParent = function (parent) { - var _parentage = this._parentage; - return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent)); - }; - Subscription.prototype._addParent = function (parent) { - var _parentage = this._parentage; - this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent; - }; - Subscription.prototype._removeParent = function (parent) { - var _parentage = this._parentage; - if (_parentage === parent) { - this._parentage = null; - } - else if (Array.isArray(_parentage)) { - arrRemove(_parentage, parent); - } - }; - Subscription.prototype.remove = function (teardown) { - var _finalizers = this._finalizers; - _finalizers && arrRemove(_finalizers, teardown); - if (teardown instanceof Subscription) { - teardown._removeParent(this); - } - }; - Subscription.EMPTY = (function () { - var empty = new Subscription(); - empty.closed = true; - return empty; - })(); - return Subscription; -}()); -Subscription.EMPTY; -function isSubscription(value) { - return (value instanceof Subscription || - (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))); -} -function execFinalizer(finalizer) { - if (isFunction(finalizer)) { - finalizer(); - } - else { - finalizer.unsubscribe(); - } -} - -var config = { - onUnhandledError: null, - onStoppedNotification: null, - Promise: undefined, - useDeprecatedSynchronousErrorHandling: false, - useDeprecatedNextContext: false, -}; - -var timeoutProvider = { - setTimeout: function (handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = timeoutProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) { - return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args))); - } - return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args))); - }, - clearTimeout: function (handle) { - var delegate = timeoutProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle); - }, - delegate: undefined, -}; - -function reportUnhandledError(err) { - timeoutProvider.setTimeout(function () { - { - throw err; - } - }); -} - -function noop() { } - -function errorContext(cb) { - { - cb(); - } -} - -var Subscriber = (function (_super) { - __extends(Subscriber, _super); - function Subscriber(destination) { - var _this = _super.call(this) || this; - _this.isStopped = false; - if (destination) { - _this.destination = destination; - if (isSubscription(destination)) { - destination.add(_this); - } - } - else { - _this.destination = EMPTY_OBSERVER; - } - return _this; - } - Subscriber.create = function (next, error, complete) { - return new SafeSubscriber(next, error, complete); - }; - Subscriber.prototype.next = function (value) { - if (this.isStopped) ; - else { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (this.isStopped) ; - else { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (this.isStopped) ; - else { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (!this.closed) { - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - this.destination = null; - } - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - try { - this.destination.error(err); - } - finally { - this.unsubscribe(); - } - }; - Subscriber.prototype._complete = function () { - try { - this.destination.complete(); - } - finally { - this.unsubscribe(); - } - }; - return Subscriber; -}(Subscription)); -var _bind = Function.prototype.bind; -function bind(fn, thisArg) { - return _bind.call(fn, thisArg); -} -var ConsumerObserver = (function () { - function ConsumerObserver(partialObserver) { - this.partialObserver = partialObserver; - } - ConsumerObserver.prototype.next = function (value) { - var partialObserver = this.partialObserver; - if (partialObserver.next) { - try { - partialObserver.next(value); - } - catch (error) { - handleUnhandledError(error); - } - } - }; - ConsumerObserver.prototype.error = function (err) { - var partialObserver = this.partialObserver; - if (partialObserver.error) { - try { - partialObserver.error(err); - } - catch (error) { - handleUnhandledError(error); - } - } - else { - handleUnhandledError(err); - } - }; - ConsumerObserver.prototype.complete = function () { - var partialObserver = this.partialObserver; - if (partialObserver.complete) { - try { - partialObserver.complete(); - } - catch (error) { - handleUnhandledError(error); - } - } - }; - return ConsumerObserver; -}()); -var SafeSubscriber = (function (_super) { - __extends(SafeSubscriber, _super); - function SafeSubscriber(observerOrNext, error, complete) { - var _this = _super.call(this) || this; - var partialObserver; - if (isFunction(observerOrNext) || !observerOrNext) { - partialObserver = { - next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined), - error: error !== null && error !== void 0 ? error : undefined, - complete: complete !== null && complete !== void 0 ? complete : undefined, - }; - } - else { - var context_1; - if (_this && config.useDeprecatedNextContext) { - context_1 = Object.create(observerOrNext); - context_1.unsubscribe = function () { return _this.unsubscribe(); }; - partialObserver = { - next: observerOrNext.next && bind(observerOrNext.next, context_1), - error: observerOrNext.error && bind(observerOrNext.error, context_1), - complete: observerOrNext.complete && bind(observerOrNext.complete, context_1), - }; - } - else { - partialObserver = observerOrNext; - } - } - _this.destination = new ConsumerObserver(partialObserver); - return _this; - } - return SafeSubscriber; -}(Subscriber)); -function handleUnhandledError(error) { - { - reportUnhandledError(error); - } -} -function defaultErrorHandler(err) { - throw err; -} -var EMPTY_OBSERVER = { - closed: true, - next: noop, - error: defaultErrorHandler, - complete: noop, -}; - -var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })(); - -function identity(x) { - return x; -} - -function pipeFromArray(fns) { - if (fns.length === 0) { - return identity; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; -} - -var Observable = (function () { - function Observable(subscribe) { - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var _this = this; - var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete); - errorContext(function () { - var _a = _this, operator = _a.operator, source = _a.source; - subscriber.add(operator - ? - operator.call(subscriber, source) - : source - ? - _this._subscribe(subscriber) - : - _this._trySubscribe(subscriber)); - }); - return subscriber; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - sink.error(err); - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscriber = new SafeSubscriber({ - next: function (value) { - try { - next(value); - } - catch (err) { - reject(err); - subscriber.unsubscribe(); - } - }, - error: reject, - complete: resolve, - }); - _this.subscribe(subscriber); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var _a; - return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; -}()); -function getPromiseCtor(promiseCtor) { - var _a; - return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise; -} -function isObserver(value) { - return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete); -} -function isSubscriber(value) { - return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value)); -} - -function isInteropObservable(input) { - return isFunction(input[observable]); -} - -function isAsyncIterable(obj) { - return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]); -} - -function createInvalidObservableTypeError(input) { - return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable."); -} - -function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; -} -var iterator = getSymbolIterator(); - -function isIterable(input) { - return isFunction(input === null || input === void 0 ? void 0 : input[iterator]); -} - -function readableStreamLikeToAsyncGenerator(readableStream) { - return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() { - var reader, _a, value, done; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - reader = readableStream.getReader(); - _b.label = 1; - case 1: - _b.trys.push([1, , 9, 10]); - _b.label = 2; - case 2: - return [4, __await(reader.read())]; - case 3: - _a = _b.sent(), value = _a.value, done = _a.done; - if (!done) return [3, 5]; - return [4, __await(void 0)]; - case 4: return [2, _b.sent()]; - case 5: return [4, __await(value)]; - case 6: return [4, _b.sent()]; - case 7: - _b.sent(); - return [3, 2]; - case 8: return [3, 10]; - case 9: - reader.releaseLock(); - return [7]; - case 10: return [2]; - } - }); - }); -} -function isReadableStreamLike(obj) { - return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader); -} - -function innerFrom(input) { - if (input instanceof Observable) { - return input; - } - if (input != null) { - if (isInteropObservable(input)) { - return fromInteropObservable(input); - } - if (isArrayLike(input)) { - return fromArrayLike(input); - } - if (isPromise(input)) { - return fromPromise(input); - } - if (isAsyncIterable(input)) { - return fromAsyncIterable(input); - } - if (isIterable(input)) { - return fromIterable(input); - } - if (isReadableStreamLike(input)) { - return fromReadableStreamLike(input); - } - } - throw createInvalidObservableTypeError(input); -} -function fromInteropObservable(obj) { - return new Observable(function (subscriber) { - var obs = obj[observable](); - if (isFunction(obs.subscribe)) { - return obs.subscribe(subscriber); - } - throw new TypeError('Provided object does not correctly implement Symbol.observable'); - }); -} -function fromArrayLike(array) { - return new Observable(function (subscriber) { - for (var i = 0; i < array.length && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }); -} -function fromPromise(promise) { - return new Observable(function (subscriber) { - promise - .then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, reportUnhandledError); - }); -} -function fromIterable(iterable) { - return new Observable(function (subscriber) { - var e_1, _a; - try { - for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) { - var value = iterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1); - } - finally { if (e_1) throw e_1.error; } - } - subscriber.complete(); - }); -} -function fromAsyncIterable(asyncIterable) { - return new Observable(function (subscriber) { - process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); }); - }); -} -function fromReadableStreamLike(readableStream) { - return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream)); -} -function process(asyncIterable, subscriber) { - var asyncIterable_1, asyncIterable_1_1; - var e_2, _a; - return __awaiter(this, void 0, void 0, function () { - var value, e_2_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 5, 6, 11]); - asyncIterable_1 = __asyncValues(asyncIterable); - _b.label = 1; - case 1: return [4, asyncIterable_1.next()]; - case 2: - if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4]; - value = asyncIterable_1_1.value; - subscriber.next(value); - if (subscriber.closed) { - return [2]; - } - _b.label = 3; - case 3: return [3, 1]; - case 4: return [3, 11]; - case 5: - e_2_1 = _b.sent(); - e_2 = { error: e_2_1 }; - return [3, 11]; - case 6: - _b.trys.push([6, , 9, 10]); - if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8]; - return [4, _a.call(asyncIterable_1)]; - case 7: - _b.sent(); - _b.label = 8; - case 8: return [3, 10]; - case 9: - if (e_2) throw e_2.error; - return [7]; - case 10: return [7]; - case 11: - subscriber.complete(); - return [2]; - } - }); - }); -} - -function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) { - return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize); -} -var OperatorSubscriber = (function (_super) { - __extends(OperatorSubscriber, _super); - function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) { - var _this = _super.call(this, destination) || this; - _this.onFinalize = onFinalize; - _this.shouldUnsubscribe = shouldUnsubscribe; - _this._next = onNext - ? function (value) { - try { - onNext(value); - } - catch (err) { - destination.error(err); - } - } - : _super.prototype._next; - _this._error = onError - ? function (err) { - try { - onError(err); - } - catch (err) { - destination.error(err); - } - finally { - this.unsubscribe(); - } - } - : _super.prototype._error; - _this._complete = onComplete - ? function () { - try { - onComplete(); - } - catch (err) { - destination.error(err); - } - finally { - this.unsubscribe(); - } - } - : _super.prototype._complete; - return _this; - } - OperatorSubscriber.prototype.unsubscribe = function () { - var _a; - if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) { - var closed_1 = this.closed; - _super.prototype.unsubscribe.call(this); - !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this)); - } - }; - return OperatorSubscriber; -}(Subscriber)); - -var Action = (function (_super) { - __extends(Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - return this; - }; - return Action; -}(Subscription)); - -var intervalProvider = { - setInterval: function (handler, timeout) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var delegate = intervalProvider.delegate; - if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) { - return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args))); - } - return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args))); - }, - clearInterval: function (handle) { - var delegate = intervalProvider.delegate; - return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle); - }, - delegate: undefined, -}; - -var AsyncAction = (function (_super) { - __extends(AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { delay = 0; } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) { - if (delay === void 0) { delay = 0; } - return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) { - if (delay === void 0) { delay = 0; } - if (delay != null && this.delay === delay && this.pending === false) { - return id; - } - intervalProvider.clearInterval(id); - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, _delay) { - var errored = false; - var errorValue; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = e ? e : new Error('Scheduled action threw falsy error'); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype.unsubscribe = function () { - if (!this.closed) { - var _a = this, id = _a.id, scheduler = _a.scheduler; - var actions = scheduler.actions; - this.work = this.state = this.scheduler = null; - this.pending = false; - arrRemove(actions, this); - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - _super.prototype.unsubscribe.call(this); - } - }; - return AsyncAction; -}(Action)); - -var dateTimestampProvider = { - now: function () { - return (dateTimestampProvider.delegate || Date).now(); - }, - delegate: undefined, -}; - -var Scheduler = (function () { - function Scheduler(schedulerActionCtor, now) { - if (now === void 0) { now = Scheduler.now; } - this.schedulerActionCtor = schedulerActionCtor; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { delay = 0; } - return new this.schedulerActionCtor(this, work).schedule(state, delay); - }; - Scheduler.now = dateTimestampProvider.now; - return Scheduler; -}()); - -var AsyncScheduler = (function (_super) { - __extends(AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { now = Scheduler.now; } - var _this = _super.call(this, SchedulerAction, now) || this; - _this.actions = []; - _this._active = false; - _this._scheduled = undefined; - return _this; - } - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this._active) { - actions.push(action); - return; - } - var error; - this._active = true; - do { - if ((error = action.execute(action.state, action.delay))) { - break; - } - } while ((action = actions.shift())); - this._active = false; - if (error) { - while ((action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; -}(Scheduler)); - -var asyncScheduler = new AsyncScheduler(AsyncAction); -var async = asyncScheduler; - -function isScheduler(value) { - return value && isFunction(value.schedule); -} - -function isValidDate(value) { - return value instanceof Date && !isNaN(value); -} - -function timer(dueTime, intervalOrScheduler, scheduler) { - if (dueTime === void 0) { dueTime = 0; } - if (scheduler === void 0) { scheduler = async; } - var intervalDuration = -1; - if (intervalOrScheduler != null) { - if (isScheduler(intervalOrScheduler)) { - scheduler = intervalOrScheduler; - } - else { - intervalDuration = intervalOrScheduler; - } - } - return new Observable(function (subscriber) { - var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime; - if (due < 0) { - due = 0; - } - var n = 0; - return scheduler.schedule(function () { - if (!subscriber.closed) { - subscriber.next(n++); - if (0 <= intervalDuration) { - this.schedule(undefined, intervalDuration); - } - else { - subscriber.complete(); - } - } - }, due); - }); -} - -function last(arr) { - return arr[arr.length - 1]; -} -function popScheduler(args) { - return isScheduler(last(args)) ? args.pop() : undefined; -} - -function executeSchedule(parentSubscription, scheduler, work, delay, repeat) { - if (delay === void 0) { delay = 0; } - if (repeat === void 0) { repeat = false; } - var scheduleSubscription = scheduler.schedule(function () { - work(); - if (repeat) { - parentSubscription.add(this.schedule(null, delay)); - } - else { - this.unsubscribe(); - } - }, delay); - parentSubscription.add(scheduleSubscription); - if (!repeat) { - return scheduleSubscription; - } -} - -function catchError(selector) { - return operate(function (source, subscriber) { - var innerSub = null; - var syncUnsub = false; - var handledResult; - innerSub = source.subscribe(createOperatorSubscriber(subscriber, undefined, undefined, function (err) { - handledResult = innerFrom(selector(err, catchError(selector)(source))); - if (innerSub) { - innerSub.unsubscribe(); - innerSub = null; - handledResult.subscribe(subscriber); - } - else { - syncUnsub = true; - } - })); - if (syncUnsub) { - innerSub.unsubscribe(); - innerSub = null; - handledResult.subscribe(subscriber); - } - }); -} - -function observeOn(scheduler, delay) { - if (delay === void 0) { delay = 0; } - return operate(function (source, subscriber) { - source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); })); - }); -} - -function subscribeOn(scheduler, delay) { - if (delay === void 0) { delay = 0; } - return operate(function (source, subscriber) { - subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay)); - }); -} - -function scheduleObservable(input, scheduler) { - return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler)); -} - -function schedulePromise(input, scheduler) { - return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler)); -} - -function scheduleArray(input, scheduler) { - return new Observable(function (subscriber) { - var i = 0; - return scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - } - else { - subscriber.next(input[i++]); - if (!subscriber.closed) { - this.schedule(); - } - } - }); - }); -} - -function scheduleIterable(input, scheduler) { - return new Observable(function (subscriber) { - var iterator$1; - executeSchedule(subscriber, scheduler, function () { - iterator$1 = input[iterator](); - executeSchedule(subscriber, scheduler, function () { - var _a; - var value; - var done; - try { - (_a = iterator$1.next(), value = _a.value, done = _a.done); - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - } - }, 0, true); - }); - return function () { return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); }; - }); -} - -function scheduleAsyncIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); - } - return new Observable(function (subscriber) { - executeSchedule(subscriber, scheduler, function () { - var iterator = input[Symbol.asyncIterator](); - executeSchedule(subscriber, scheduler, function () { - iterator.next().then(function (result) { - if (result.done) { - subscriber.complete(); - } - else { - subscriber.next(result.value); - } - }); - }, 0, true); - }); - }); -} - -function scheduleReadableStreamLike(input, scheduler) { - return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler); -} - -function scheduled(input, scheduler) { - if (input != null) { - if (isInteropObservable(input)) { - return scheduleObservable(input, scheduler); - } - if (isArrayLike(input)) { - return scheduleArray(input, scheduler); - } - if (isPromise(input)) { - return schedulePromise(input, scheduler); - } - if (isAsyncIterable(input)) { - return scheduleAsyncIterable(input, scheduler); - } - if (isIterable(input)) { - return scheduleIterable(input, scheduler); - } - if (isReadableStreamLike(input)) { - return scheduleReadableStreamLike(input, scheduler); - } - } - throw createInvalidObservableTypeError(input); -} - -function from(input, scheduler) { - return scheduler ? scheduled(input, scheduler) : innerFrom(input); -} - -function map(project, thisArg) { - return operate(function (source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - subscriber.next(project.call(thisArg, value, index++)); - })); - }); -} - -function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) { - var buffer = []; - var active = 0; - var index = 0; - var isComplete = false; - var checkComplete = function () { - if (isComplete && !buffer.length && !active) { - subscriber.complete(); - } - }; - var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); }; - var doInnerSub = function (value) { - expand && subscriber.next(value); - active++; - var innerComplete = false; - innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) { - onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue); - if (expand) { - outerNext(innerValue); - } - else { - subscriber.next(innerValue); - } - }, function () { - innerComplete = true; - }, undefined, function () { - if (innerComplete) { - try { - active--; - var _loop_1 = function () { - var bufferedValue = buffer.shift(); - if (innerSubScheduler) { - executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); }); - } - else { - doInnerSub(bufferedValue); - } - }; - while (buffer.length && active < concurrent) { - _loop_1(); - } - checkComplete(); - } - catch (err) { - subscriber.error(err); - } - } - })); - }; - source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () { - isComplete = true; - checkComplete(); - })); - return function () { - additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer(); - }; -} - -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { concurrent = Infinity; } - if (isFunction(resultSelector)) { - return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent); - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); }); -} - -function mergeAll(concurrent) { - if (concurrent === void 0) { concurrent = Infinity; } - return mergeMap(identity, concurrent); -} - -function concatAll() { - return mergeAll(1); -} - -function debounceTime(dueTime, scheduler) { - if (scheduler === void 0) { scheduler = asyncScheduler; } - return operate(function (source, subscriber) { - var activeTask = null; - var lastValue = null; - var lastTime = null; - var emit = function () { - if (activeTask) { - activeTask.unsubscribe(); - activeTask = null; - var value = lastValue; - lastValue = null; - subscriber.next(value); - } - }; - function emitWhenIdle() { - var targetTime = lastTime + dueTime; - var now = scheduler.now(); - if (now < targetTime) { - activeTask = this.schedule(undefined, targetTime - now); - subscriber.add(activeTask); - return; - } - emit(); - } - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - lastValue = value; - lastTime = scheduler.now(); - if (!activeTask) { - activeTask = scheduler.schedule(emitWhenIdle, dueTime); - subscriber.add(activeTask); - } - }, function () { - emit(); - subscriber.complete(); - }, undefined, function () { - lastValue = activeTask = null; - })); - }); -} - -function concat$1() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return concatAll()(from(args, popScheduler(args))); -} - -var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); }); - -function take(count) { - return count <= 0 - ? - function () { return EMPTY; } - : operate(function (source, subscriber) { - var seen = 0; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - if (++seen <= count) { - subscriber.next(value); - if (count <= seen) { - subscriber.complete(); - } - } - })); - }); -} - -function ignoreElements() { - return operate(function (source, subscriber) { - source.subscribe(createOperatorSubscriber(subscriber, noop)); - }); -} - -function mapTo(value) { - return map(function () { return value; }); -} - -function delayWhen(delayDurationSelector, subscriptionDelay) { - if (subscriptionDelay) { - return function (source) { - return concat$1(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector))); - }; - } - return mergeMap(function (value, index) { return delayDurationSelector(value, index).pipe(take(1), mapTo(value)); }); -} - -function delay(due, scheduler) { - if (scheduler === void 0) { scheduler = asyncScheduler; } - var duration = timer(due, scheduler); - return delayWhen(function () { return duration; }); -} - -function distinctUntilChanged(comparator, keySelector) { - if (keySelector === void 0) { keySelector = identity; } - comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare; - return operate(function (source, subscriber) { - var previousKey; - var first = true; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - var currentKey = keySelector(value); - if (first || !comparator(previousKey, currentKey)) { - first = false; - previousKey = currentKey; - subscriber.next(value); - } - })); - }); -} -function defaultCompare(a, b) { - return a === b; -} - -function filter(predicate, thisArg) { - return operate(function (source, subscriber) { - var index = 0; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); })); - }); -} - -function skip(count) { - return filter(function (_, index) { return count <= index; }); -} - -function startWith() { - var values = []; - for (var _i = 0; _i < arguments.length; _i++) { - values[_i] = arguments[_i]; - } - var scheduler = popScheduler(values); - return operate(function (source, subscriber) { - (scheduler ? concat$1(values, source, scheduler) : concat$1(values, source)).subscribe(subscriber); - }); -} - -function switchMap(project, resultSelector) { - return operate(function (source, subscriber) { - var innerSubscriber = null; - var index = 0; - var isComplete = false; - var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); }; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe(); - var innerIndex = 0; - var outerIndex = index++; - innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () { - innerSubscriber = null; - checkComplete(); - }))); - }, function () { - isComplete = true; - checkComplete(); - })); - }); -} - -function tap(observerOrNext, error, complete) { - var tapObserver = isFunction(observerOrNext) || error || complete - ? - { next: observerOrNext, error: error, complete: complete } - : observerOrNext; - return tapObserver - ? operate(function (source, subscriber) { - var _a; - (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver); - var isUnsub = true; - source.subscribe(createOperatorSubscriber(subscriber, function (value) { - var _a; - (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value); - subscriber.next(value); - }, function () { - var _a; - isUnsub = false; - (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver); - subscriber.complete(); - }, function (err) { - var _a; - isUnsub = false; - (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err); - subscriber.error(err); - }, function () { - var _a, _b; - if (isUnsub) { - (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver); - } - (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver); - })); - }) - : - identity; -} - -//const hasSW = 'serviceWorker' in navigator; -let hasComplainedAboutSyncEvent = false; -function registerSyncEvent(db, purpose) { - return __awaiter(this, void 0, void 0, function* () { - try { - // Send sync event to SW: - const sw = yield navigator.serviceWorker.ready; - if (purpose === "push" && sw.sync) { - yield sw.sync.register(`dexie-cloud:${db.name}`); - } - if (sw.active) { - // Use postMessage for pull syncs and for browsers not supporting sync event (Firefox, Safari). - // Also chromium based browsers with sw.sync as a fallback for sleepy sync events not taking action for a while. - sw.active.postMessage({ - type: 'dexie-cloud-sync', - dbName: db.name, - purpose - }); - } - else { - throw new Error(`Failed to trigger sync - there's no active service worker`); - } - return; - } - catch (e) { - if (!hasComplainedAboutSyncEvent) { - console.debug(`Dexie Cloud: Could not register sync event`, e); - hasComplainedAboutSyncEvent = true; - } - } - }); -} -function registerPeriodicSyncEvent(db) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - try { - // Register periodicSync event to SW: - // @ts-ignore - const { periodicSync } = yield navigator.serviceWorker.ready; - if (periodicSync) { - try { - yield periodicSync.register(`dexie-cloud:${db.name}`, (_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.periodicSync); - console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${db.name}`); - } - catch (e) { - console.debug(`Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.`, e); - } - } - else { - console.debug(`Dexie Cloud: periodicSync not supported.`); - } - } - catch (e) { - console.debug(`Dexie Cloud: Could not register periodicSync for ${db.name}`, e); - } - }); -} - -function triggerSync(db, purpose) { - if (db.cloud.usingServiceWorker) { - console.debug('registering sync event'); - registerSyncEvent(db, purpose); - } - else { - db.localSyncEvent.next({ purpose }); - } -} - -const b64decode = typeof Buffer !== "undefined" - ? (base64) => Buffer.from(base64, "base64") - : (base64) => { - const binary_string = atob(base64); - const len = binary_string.length; - const bytes = new Uint8Array(len); - for (var i = 0; i < len; i++) { - bytes[i] = binary_string.charCodeAt(i); - } - return bytes; - }; -const b64encode = typeof Buffer !== "undefined" - ? (b) => { - if (ArrayBuffer.isView(b)) { - return Buffer.from(b.buffer, b.byteOffset, b.byteLength).toString("base64"); - } - else { - return Buffer.from(b).toString("base64"); - } - } - : (b) => { - const u8a = ArrayBuffer.isView(b) ? b : new Uint8Array(b); - const CHUNK_SIZE = 0x1000; - const strs = []; - for (let i = 0, l = u8a.length; i < l; i += CHUNK_SIZE) { - const chunk = u8a.subarray(i, i + CHUNK_SIZE); - strs.push(String.fromCharCode.apply(null, chunk)); - } - return btoa(strs.join("")); - }; - -class TokenErrorResponseError extends Error { - constructor({ title, message, messageCode, messageParams, }) { - super(message); - this.name = 'TokenErrorResponseError'; - this.title = title; - this.messageCode = messageCode; - this.messageParams = messageParams; - } -} - -function interactWithUser(userInteraction, req) { - return new Promise((resolve, reject) => { - const interactionProps = Object.assign(Object.assign({ submitLabel: 'Submit', cancelLabel: 'Cancel' }, req), { onSubmit: (res) => { - userInteraction.next(undefined); - resolve(res); - }, onCancel: () => { - userInteraction.next(undefined); - reject(new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].AbortError('User cancelled')); - } }); - userInteraction.next(interactionProps); - // Start subscribing for external updates to db.cloud.userInteraction, and if so, cancel this request. - /*const subscription = userInteraction.subscribe((currentInteractionProps) => { - if (currentInteractionProps !== interactionProps) { - if (subscription) subscription.unsubscribe(); - if (!done) { - reject(new Dexie.AbortError("User cancelled")); - } - } - });*/ - }); -} -function alertUser(userInteraction, title, ...alerts) { - return interactWithUser(userInteraction, { - type: 'message-alert', - title, - alerts, - fields: {}, - submitLabel: 'OK', - cancelLabel: null, - }); -} -function promptForEmail(userInteraction, title, emailHint) { - return __awaiter(this, void 0, void 0, function* () { - let email = emailHint || ''; - // Regular expression for email validation - // ^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$ - // - // ^[\w-+.]+ : Matches the start of the string. Allows one or more word characters - // (a-z, A-Z, 0-9, and underscore), hyphen, plus, or dot. - // - // @ : Matches the @ symbol. - // ([\w-]+\.)+ : Matches one or more word characters or hyphens followed by a dot. - // The plus sign outside the parentheses means this pattern can repeat one or more times, - // allowing for subdomains. - // [\w-]{2,10} : Matches between 2 and 10 word characters or hyphens. This is typically for - // the domain extension like .com, .net, etc. - // (\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$ : This part is optional (due to the ? at the end). - // If present, it matches " as " followed by another valid email address. This allows for the - // input to be either a single email address or two email addresses separated by " as ". - // - // The use case for " as "" is for when a database owner with full access to the - // database needs to impersonate another user in the database in order to troubleshoot. This - // format will only be possible to use when email1 is the owner of an API client with GLOBAL_READ - // and GLOBAL_WRITE permissions on the database. The email will be checked on the server before - // allowing it and giving out a token for email2, using the OTP sent to email1. - while (!email || !/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(email)) { - email = (yield interactWithUser(userInteraction, { - type: 'email', - title, - alerts: email - ? [ - { - type: 'error', - messageCode: 'INVALID_EMAIL', - message: 'Please enter a valid email address', - messageParams: {}, - }, - ] - : [], - fields: { - email: { - type: 'email', - placeholder: 'you@somedomain.com', - }, - }, - })).email; - } - return email; - }); -} -function promptForOTP(userInteraction, email, alert) { - return __awaiter(this, void 0, void 0, function* () { - const alerts = [ - { - type: 'info', - messageCode: 'OTP_SENT', - message: `A One-Time password has been sent to {email}`, - messageParams: { email }, - }, - ]; - if (alert) { - alerts.push(alert); - } - const { otp } = yield interactWithUser(userInteraction, { - type: 'otp', - title: 'Enter OTP', - alerts, - fields: { - otp: { - type: 'otp', - label: 'OTP', - placeholder: 'Paste OTP here', - }, - }, - }); - return otp; - }); -} -function confirmLogout(userInteraction, currentUserId, numUnsyncedChanges) { - return __awaiter(this, void 0, void 0, function* () { - const alerts = [ - { - type: 'warning', - messageCode: 'LOGOUT_CONFIRMATION', - message: `{numUnsyncedChanges} unsynced changes will get lost! - Logout anyway?`, - messageParams: { - currentUserId, - numUnsyncedChanges: numUnsyncedChanges.toString(), - } - }, - ]; - return yield interactWithUser(userInteraction, { - type: 'logout-confirmation', - title: 'Confirm Logout', - alerts, - fields: {}, - submitLabel: 'Confirm logout', - cancelLabel: 'Cancel' - }) - .then(() => true) - .catch(() => false); - }); -} - -function loadAccessToken(db) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const currentUser = yield db.getCurrentUser(); - const { accessToken, accessTokenExpiration, refreshToken, refreshTokenExpiration, claims, } = currentUser; - if (!accessToken) - return null; - const expTime = (_a = accessTokenExpiration === null || accessTokenExpiration === void 0 ? void 0 : accessTokenExpiration.getTime()) !== null && _a !== void 0 ? _a : Infinity; - if (expTime > Date.now() && (((_b = currentUser.license) === null || _b === void 0 ? void 0 : _b.status) || 'ok') === 'ok') { - return currentUser; - } - if (!refreshToken) { - throw new Error(`Refresh token missing`); - } - const refreshExpTime = (_c = refreshTokenExpiration === null || refreshTokenExpiration === void 0 ? void 0 : refreshTokenExpiration.getTime()) !== null && _c !== void 0 ? _c : Infinity; - if (refreshExpTime <= Date.now()) { - throw new Error(`Refresh token has expired`); - } - const refreshedLogin = yield refreshAccessToken(db.cloud.options.databaseUrl, currentUser); - yield db.table('$logins').update(claims.sub, { - accessToken: refreshedLogin.accessToken, - accessTokenExpiration: refreshedLogin.accessTokenExpiration, - claims: refreshedLogin.claims, - license: refreshedLogin.license, - }); - return refreshedLogin; - }); -} -function authenticate(url, context, fetchToken, userInteraction, hints) { - return __awaiter(this, void 0, void 0, function* () { - if (context.accessToken && - context.accessTokenExpiration.getTime() > Date.now()) { - return context; - } - else if (context.refreshToken && - (!context.refreshTokenExpiration || - context.refreshTokenExpiration.getTime() > Date.now())) { - return yield refreshAccessToken(url, context); - } - else { - return yield userAuthenticate(context, fetchToken, userInteraction, hints); - } - }); -} -function refreshAccessToken(url, login) { - return __awaiter(this, void 0, void 0, function* () { - if (!login.refreshToken) - throw new Error(`Cannot refresh token - refresh token is missing.`); - if (!login.nonExportablePrivateKey) - throw new Error(`login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.`); - const time_stamp = Date.now(); - const signing_algorithm = 'RSASSA-PKCS1-v1_5'; - const textEncoder = new TextEncoder(); - const data = textEncoder.encode(login.refreshToken + time_stamp); - const binarySignature = yield crypto.subtle.sign(signing_algorithm, login.nonExportablePrivateKey, data); - const signature = b64encode(binarySignature); - const tokenRequest = { - grant_type: 'refresh_token', - refresh_token: login.refreshToken, - scopes: ['ACCESS_DB'], - signature, - signing_algorithm, - time_stamp, - }; - const res = yield fetch(`${url}/token`, { - body: JSON.stringify(tokenRequest), - method: 'post', - headers: { 'Content-Type': 'application/json' }, - mode: 'cors', - }); - if (res.status !== 200) - throw new Error(`RefreshToken: Status ${res.status} from ${url}/token`); - const response = yield res.json(); - if (response.type === 'error') { - throw new TokenErrorResponseError(response); - } - login.accessToken = response.accessToken; - login.accessTokenExpiration = response.accessTokenExpiration - ? new Date(response.accessTokenExpiration) - : undefined; - login.claims = response.claims; - login.license = { - type: response.userType, - status: response.claims.license || 'ok', - }; - if (response.evalDaysLeft != null) { - login.license.evalDaysLeft = response.evalDaysLeft; - } - if (response.userValidUntil != null) { - login.license.validUntil = new Date(response.userValidUntil); - } - return login; - }); -} -function userAuthenticate(context, fetchToken, userInteraction, hints) { - return __awaiter(this, void 0, void 0, function* () { - if (!crypto.subtle) { - if (typeof location !== 'undefined' && location.protocol === 'http:') { - throw new Error(`Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost: (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)`); - } - else { - throw new Error(`This browser does not support WebCrypto.`); - } - } - const { privateKey, publicKey } = yield crypto.subtle.generateKey({ - name: 'RSASSA-PKCS1-v1_5', - modulusLength: 2048, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - hash: { name: 'SHA-256' }, - }, false, // Non-exportable... - ['sign', 'verify']); - if (!privateKey || !publicKey) - throw new Error(`Could not generate RSA keypair`); // Typings suggest these can be undefined... - context.nonExportablePrivateKey = privateKey; //...but storable! - const publicKeySPKI = yield crypto.subtle.exportKey('spki', publicKey); - const publicKeyPEM = spkiToPEM(publicKeySPKI); - context.publicKey = publicKey; - try { - const response2 = yield fetchToken({ - public_key: publicKeyPEM, - hints, - }); - if (response2.type === 'error') { - throw new TokenErrorResponseError(response2); - } - if (response2.type !== 'tokens') - throw new Error(`Unexpected response type from token endpoint: ${response2.type}`); - /*const licenseStatus = response2.claims.license || 'ok'; - if (licenseStatus !== 'ok') { - throw new InvalidLicenseError(licenseStatus); - }*/ - context.accessToken = response2.accessToken; - context.accessTokenExpiration = new Date(response2.accessTokenExpiration); - context.refreshToken = response2.refreshToken; - if (response2.refreshTokenExpiration) { - context.refreshTokenExpiration = new Date(response2.refreshTokenExpiration); - } - context.userId = response2.claims.sub; - context.email = response2.claims.email; - context.name = response2.claims.name; - context.claims = response2.claims; - context.license = { - type: response2.userType, - status: response2.claims.license || 'ok', - }; - if (response2.evalDaysLeft != null) { - context.license.evalDaysLeft = response2.evalDaysLeft; - } - if (response2.userValidUntil != null) { - context.license.validUntil = new Date(response2.userValidUntil); - } - if (response2.alerts && response2.alerts.length > 0) { - yield interactWithUser(userInteraction, { - type: 'message-alert', - title: 'Authentication Alert', - fields: {}, - alerts: response2.alerts, - }); - } - return context; - } - catch (error) { - if (error instanceof TokenErrorResponseError) { - yield alertUser(userInteraction, error.title, { - type: 'error', - messageCode: error.messageCode, - message: error.message, - messageParams: {}, - }); - throw error; - } - let message = `We're having a problem authenticating right now.`; - console.error(`Error authenticating`, error); - if (error instanceof TypeError) { - const isOffline = typeof navigator !== undefined && !navigator.onLine; - if (isOffline) { - message = `You seem to be offline. Please connect to the internet and try again.`; - } - else if (dexie__WEBPACK_IMPORTED_MODULE_0__["default"].debug || (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1'))) { - // The audience is most likely the developer. Suggest to whitelist the localhost origin: - message = `Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``; - } - else { - message = `Could not connect to server. Please verify the connection.`; - } - yield alertUser(userInteraction, 'Authentication Failed', { - type: 'error', - messageCode: 'GENERIC_ERROR', - message, - messageParams: {}, - }).catch(() => { }); - } - throw error; - } - }); -} -function spkiToPEM(keydata) { - const keydataB64 = b64encode(keydata); - const keydataB64Pem = formatAsPem(keydataB64); - return keydataB64Pem; -} -function formatAsPem(str) { - let finalString = '-----BEGIN PUBLIC KEY-----\n'; - while (str.length > 0) { - finalString += str.substring(0, 64) + '\n'; - str = str.substring(64); - } - finalString = finalString + '-----END PUBLIC KEY-----'; - return finalString; -} - -// Emulate true-private property db. Why? So it's not stored in DB. -const wm$1 = new WeakMap(); -class AuthPersistedContext { - constructor(db, userLogin) { - wm$1.set(this, db); - Object.assign(this, userLogin); - } - static load(db, userId) { - return db - .table("$logins") - .get(userId) - .then((userLogin) => new AuthPersistedContext(db, userLogin || { - userId, - claims: { - sub: userId - }, - lastLogin: new Date(0) - })); - } - save() { - return __awaiter(this, void 0, void 0, function* () { - const db = wm$1.get(this); - db.table("$logins").put(this); - }); - } -} - -const UNAUTHORIZED_USER = { - userId: "unauthorized", - name: "Unauthorized", - claims: { - sub: "unauthorized", - }, - lastLogin: new Date(0) -}; -try { - Object.freeze(UNAUTHORIZED_USER); - Object.freeze(UNAUTHORIZED_USER.claims); -} -catch (_a) { } - -function waitUntil(o, // Works with Dexie's liveQuery observables if we'd need that -predicate) { - return (0,rxjs__WEBPACK_IMPORTED_MODULE_1__.firstValueFrom)((0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(o).pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_3__.filter)(predicate))); -} - -function logout(db) { - return __awaiter(this, void 0, void 0, function* () { - const numUnsyncedChanges = yield _logout(db); - if (numUnsyncedChanges) { - if (yield confirmLogout(db.cloud.userInteraction, db.cloud.currentUserId, numUnsyncedChanges)) { - yield _logout(db, { deleteUnsyncedData: true }); - } - else { - throw new Error(`User cancelled logout due to unsynced changes`); - } - } - }); -} -function _logout(db, { deleteUnsyncedData = false } = {}) { - return __awaiter(this, void 0, void 0, function* () { - // Clear the database without emptying configuration options. - const [numUnsynced, loggedOut] = yield db.dx.transaction('rw', db.dx.tables, (tx) => __awaiter(this, void 0, void 0, function* () { - // @ts-ignore - const idbtrans = tx.idbtrans; - idbtrans.disableChangeTracking = true; - idbtrans.disableAccessControl = true; - const mutationTables = tx.storeNames.filter((tableName) => tableName.endsWith('_mutations')); - // Count unsynced changes - const unsyncCounts = yield Promise.all(mutationTables.map((mutationTable) => tx.table(mutationTable).count())); - const sumUnSynced = unsyncCounts.reduce((a, b) => a + b, 0); - if (sumUnSynced > 0 && !deleteUnsyncedData) { - // Let caller ask user if they want to delete unsynced data. - return [sumUnSynced, false]; - } - // Either there are no unsynched changes, or caller provided flag deleteUnsynchedData = true. - // Clear all tables except $jobs and $syncState (except the persisted sync state which is - // also cleared because we're going to rebuild it using a fresh sync). - db.$syncState.delete('syncState'); - for (const table of db.dx.tables) { - if (table.name !== '$jobs' && table.name !== '$syncState') { - table.clear(); - } - } - return [sumUnSynced, true]; - })); - if (loggedOut) { - // Wait for currentUser observable to emit UNAUTHORIZED_USER - yield waitUntil(db.cloud.currentUser, (user) => user.userId === UNAUTHORIZED_USER.userId); - // Then perform an initial sync - yield db.cloud.sync({ purpose: 'pull', wait: true }); - } - return numUnsynced; - }); -} - -class HttpError extends Error { - constructor(res, message) { - super(message || `${res.status} ${res.statusText}`); - this.httpStatus = res.status; - } - get name() { - return "HttpError"; - } -} - -function otpFetchTokenCallback(db) { - const { userInteraction } = db.cloud; - return function otpAuthenticate({ public_key, hints }) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - let tokenRequest; - const url = (_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.databaseUrl; - if (!url) - throw new Error(`No database URL given.`); - if ((hints === null || hints === void 0 ? void 0 : hints.grant_type) === 'demo') { - const demo_user = yield promptForEmail(userInteraction, 'Enter a demo user email', (hints === null || hints === void 0 ? void 0 : hints.email) || (hints === null || hints === void 0 ? void 0 : hints.userId)); - tokenRequest = { - demo_user, - grant_type: 'demo', - scopes: ['ACCESS_DB'], - public_key - }; - } - else if ((hints === null || hints === void 0 ? void 0 : hints.otpId) && hints.otp) { - // User provided OTP ID and OTP code. This means that the OTP email - // has already gone out and the user may have clicked a magic link - // in the email with otp and otpId in query and the app has picked - // up those values and passed them to db.cloud.login(). - tokenRequest = { - grant_type: 'otp', - otp_id: hints.otpId, - otp: hints.otp, - scopes: ['ACCESS_DB'], - public_key, - }; - } - else { - const email = yield promptForEmail(userInteraction, 'Enter email address', hints === null || hints === void 0 ? void 0 : hints.email); - if (/@demo.local$/.test(email)) { - tokenRequest = { - demo_user: email, - grant_type: 'demo', - scopes: ['ACCESS_DB'], - public_key - }; - } - else { - tokenRequest = { - email, - grant_type: 'otp', - scopes: ['ACCESS_DB'], - }; - } - } - const res1 = yield fetch(`${url}/token`, { - body: JSON.stringify(tokenRequest), - method: 'post', - headers: { 'Content-Type': 'application/json', mode: 'cors' }, - }); - if (res1.status !== 200) { - const errMsg = yield res1.text(); - yield alertUser(userInteraction, "Token request failed", { - type: 'error', - messageCode: 'GENERIC_ERROR', - message: errMsg, - messageParams: {} - }).catch(() => { }); - throw new HttpError(res1, errMsg); - } - const response = yield res1.json(); - if (response.type === 'tokens' || response.type === 'error') { - // Demo user request can get a "tokens" response right away - // Error can also be returned right away. - return response; - } - else if (tokenRequest.grant_type === 'otp' && 'email' in tokenRequest) { - if (response.type !== 'otp-sent') - throw new Error(`Unexpected response from ${url}/token`); - const otp = yield promptForOTP(userInteraction, tokenRequest.email); - const tokenRequest2 = Object.assign(Object.assign({}, tokenRequest), { otp: otp || '', otp_id: response.otp_id, public_key }); - let res2 = yield fetch(`${url}/token`, { - body: JSON.stringify(tokenRequest2), - method: 'post', - headers: { 'Content-Type': 'application/json' }, - mode: 'cors', - }); - while (res2.status === 401) { - const errorText = yield res2.text(); - tokenRequest2.otp = yield promptForOTP(userInteraction, tokenRequest.email, { - type: 'error', - messageCode: 'INVALID_OTP', - message: errorText, - messageParams: {} - }); - res2 = yield fetch(`${url}/token`, { - body: JSON.stringify(tokenRequest2), - method: 'post', - headers: { 'Content-Type': 'application/json' }, - mode: 'cors', - }); - } - if (res2.status !== 200) { - const errMsg = yield res2.text(); - throw new HttpError(res2, errMsg); - } - const response2 = yield res2.json(); - return response2; - } - else { - throw new Error(`Unexpected response from ${url}/token`); - } - }); - }; -} - -/** A way to log to console in production without terser stripping out - * it from the release bundle. - * This should be used very rarely and only in places where it's - * absolutely necessary to log something in production. - * - * @param level - * @param args - */ -function prodLog(level, ...args) { - globalThis["con" + "sole"][level](...args); -} - -/** This function changes or sets the current user as requested. - * - * Use cases: - * * Initially on db.ready after reading the current user from db.$logins. - * This will make sure that any unsynced operations from the previous user is synced before - * changing the user. - * * Upon user request - * - * @param db - * @param newUser - */ -function setCurrentUser(db, user) { - return __awaiter(this, void 0, void 0, function* () { - if (user.userId === db.cloud.currentUserId) - return; // Already this user. - const $logins = db.table('$logins'); - yield db.transaction('rw', $logins, (tx) => __awaiter(this, void 0, void 0, function* () { - const existingLogins = yield $logins.toArray(); - yield Promise.all(existingLogins - .filter((login) => login.userId !== user.userId && login.isLoggedIn) - .map((login) => { - login.isLoggedIn = false; - return $logins.put(login); - })); - user.isLoggedIn = true; - user.lastLogin = new Date(); - try { - yield user.save(); - } - catch (e) { - try { - if (e.name === 'DataCloneError') { - // We've seen this buggy behavior in some browsers and in case it happens - // again we really need to collect the details to understand what's going on. - prodLog('debug', `Login context property names:`, Object.keys(user)); - prodLog('debug', `Login context property names:`, Object.keys(user)); - prodLog('debug', `Login context:`, user); - prodLog('debug', `Login context JSON:`, JSON.stringify(user)); - } - } - catch (_a) { } - throw e; - } - console.debug('Saved new user', user.email); - })); - yield waitUntil(db.cloud.currentUser, (currentUser) => currentUser.userId === user.userId); - }); -} - -function login(db, hints) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const currentUser = yield db.getCurrentUser(); - const origUserId = currentUser.userId; - if (currentUser.isLoggedIn && (!hints || (!hints.email && !hints.userId))) { - const licenseStatus = ((_a = currentUser.license) === null || _a === void 0 ? void 0 : _a.status) || 'ok'; - if (licenseStatus === 'ok' && currentUser.accessToken && (!currentUser.accessTokenExpiration || currentUser.accessTokenExpiration.getTime() > Date.now())) { - // Already authenticated according to given hints. And license is valid. - return false; - } - if (currentUser.refreshToken && (!currentUser.refreshTokenExpiration || currentUser.refreshTokenExpiration.getTime() > Date.now())) { - // Refresh the token - yield loadAccessToken(db); - return false; - } - // No refresh token - must re-authenticate: - } - const context = new AuthPersistedContext(db, { - claims: {}, - lastLogin: new Date(0), - }); - yield authenticate(db.cloud.options.databaseUrl, context, db.cloud.options.fetchTokens || otpFetchTokenCallback(db), db.cloud.userInteraction, hints); - if (origUserId !== UNAUTHORIZED_USER.userId && context.userId !== origUserId) { - // User was logged in before, but now logged in as another user. - yield logout(db); - } - /*try { - await context.save(); - } catch (e) { - try { - if (e.name === 'DataCloneError') { - console.debug(`Login context property names:`, Object.keys(context)); - console.debug(`Login context:`, context); - console.debug(`Login context JSON:`, JSON.stringify(context)); - } - } catch {} - throw e; - }*/ - yield setCurrentUser(db, context); - // Make sure to resync as the new login will be authorized - // for new realms. - triggerSync(db, "pull"); - return context.userId !== origUserId; - }); -} - -const swHolder = {}; -const swContainer = typeof self !== 'undefined' && self.document && // self.document is to verify we're not the SW ourself - typeof navigator !== 'undefined' && navigator.serviceWorker; -if (swContainer) - swContainer.ready.then((registration) => (swHolder.registration = registration)); -if (typeof self !== 'undefined' && 'clients' in self && !self.document) { - // We are the service worker. Propagate messages to all our clients. - addEventListener('message', (ev) => { - var _a, _b; - if ((_b = (_a = ev.data) === null || _a === void 0 ? void 0 : _a.type) === null || _b === void 0 ? void 0 : _b.startsWith('sw-broadcast-')) { - [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => { var _a; return client.id !== ((_a = ev.source) === null || _a === void 0 ? void 0 : _a.id) && client.postMessage(ev.data); }); - } - }); -} -/** This class is a fallback for browsers that lacks BroadcastChannel but have - * service workers (which is Safari versions 11.1 through 15.3). - * Safari 15.4 with BroadcastChannel was released on 2022-03-14. - * We might be able to remove this class in a near future as Safari < 15.4 is - * already very low in market share as of 2023-03-10. - */ -class SWBroadcastChannel { - constructor(name) { - this.name = name; - } - subscribe(listener) { - if (!swContainer) - return () => { }; - const forwarder = (ev) => { - var _a; - if (((_a = ev.data) === null || _a === void 0 ? void 0 : _a.type) === `sw-broadcast-${this.name}`) { - listener(ev.data.message); - } - }; - swContainer.addEventListener('message', forwarder); - return () => swContainer.removeEventListener('message', forwarder); - } - postMessage(message) { - var _a; - if (typeof self['clients'] === 'object') { - // We're a service worker. Propagate to our browser clients. - [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => client.postMessage({ - type: `sw-broadcast-${this.name}`, - message, - })); - } - else if (swHolder.registration) { - // We're a client (browser window or other worker) - // Post to SW so it can repost to all its clients and to itself - (_a = swHolder.registration.active) === null || _a === void 0 ? void 0 : _a.postMessage({ - type: `sw-broadcast-${this.name}`, - message, - }); - } - } -} - -const events = globalThis['lbc-events'] || (globalThis['lbc-events'] = new Map()); -function addListener(name, listener) { - if (events.has(name)) { - events.get(name).push(listener); - } - else { - events.set(name, [listener]); - } -} -function removeListener(name, listener) { - const listeners = events.get(name); - if (listeners) { - const idx = listeners.indexOf(listener); - if (idx !== -1) { - listeners.splice(idx, 1); - } - } -} -function dispatch(ev) { - const listeners = events.get(ev.type); - if (listeners) { - listeners.forEach(listener => { - try { - listener(ev); - } - catch (_a) { - } - }); - } -} -class BroadcastedAndLocalEvent extends rxjs__WEBPACK_IMPORTED_MODULE_4__.Observable { - constructor(name) { - const bc = typeof BroadcastChannel === "undefined" - ? new SWBroadcastChannel(name) : new BroadcastChannel(name); - super(subscriber => { - function onCustomEvent(ev) { - subscriber.next(ev.detail); - } - function onMessageEvent(ev) { - console.debug("BroadcastedAndLocalEvent: onMessageEvent", ev); - subscriber.next(ev.data); - } - let unsubscribe; - //self.addEventListener(`lbc-${name}`, onCustomEvent); // Fails in service workers - addListener(`lbc-${name}`, onCustomEvent); // Works better in service worker - try { - if (bc instanceof SWBroadcastChannel) { - unsubscribe = bc.subscribe(message => subscriber.next(message)); - } - else { - console.debug("BroadcastedAndLocalEvent: bc.addEventListener()", name, "bc is a", bc); - bc.addEventListener("message", onMessageEvent); - } - } - catch (err) { - // Service workers might fail to subscribe outside its initial script. - console.warn('Failed to subscribe to broadcast channel', err); - } - return () => { - //self.removeEventListener(`lbc-${name}`, onCustomEvent); - removeListener(`lbc-${name}`, onCustomEvent); - if (bc instanceof SWBroadcastChannel) { - unsubscribe(); - } - else { - bc.removeEventListener("message", onMessageEvent); - } - }; - }); - this.name = name; - this.bc = bc; - } - next(message) { - console.debug("BroadcastedAndLocalEvent: bc.postMessage()", Object.assign({}, message), "bc is a", this.bc); - this.bc.postMessage(message); - const ev = new CustomEvent(`lbc-${this.name}`, { detail: message }); - //self.dispatchEvent(ev); - dispatch(ev); - } -} - -function computeRealmSetHash({ realms, inviteRealms, }) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify([ - ...realms.map((realmId) => ({ realmId, accepted: true })), - ...inviteRealms.map((realmId) => ({ realmId, accepted: false })), - ].sort((a, b) => a.realmId < b.realmId ? -1 : a.realmId > b.realmId ? 1 : 0)); - const byteArray = new TextEncoder().encode(data); - const digestBytes = yield crypto.subtle.digest('SHA-1', byteArray); - const base64 = b64encode(digestBytes); - return base64; - }); -} - -function getSyncableTables(db) { - return Object.entries(db.cloud.schema || {}) - .filter(([, { markedForSync }]) => markedForSync) - .map(([tbl]) => db.tables.filter(({ name }) => name === tbl)[0]) - .filter(cloudTableSchema => cloudTableSchema); -} - -function getMutationTable(tableName) { - return `$${tableName}_mutations`; -} - -function getTableFromMutationTable(mutationTable) { - var _a; - const tableName = (_a = /^\$(.*)_mutations$/.exec(mutationTable)) === null || _a === void 0 ? void 0 : _a[1]; - if (!tableName) - throw new Error(`Given mutationTable ${mutationTable} is not correct`); - return tableName; -} - -const concat = [].concat; -function flatten(a) { - return concat.apply([], a); -} - -function listClientChanges(mutationTables, db, { since = {}, limit = Infinity } = {}) { - return __awaiter(this, void 0, void 0, function* () { - const allMutsOnTables = yield Promise.all(mutationTables.map((mutationTable) => __awaiter(this, void 0, void 0, function* () { - const tableName = getTableFromMutationTable(mutationTable.name); - const lastRevision = since[tableName]; - let query = lastRevision - ? mutationTable.where('rev').above(lastRevision) - : mutationTable; - if (limit < Infinity) - query = query.limit(limit); - const muts = yield query.toArray(); - //const objTable = db.table(tableName); - /*for (const mut of muts) { - if (mut.type === "insert" || mut.type === "upsert") { - mut.values = await objTable.bulkGet(mut.keys); - } - }*/ - return muts.map((mut) => ({ - table: tableName, - mut, - })); - }))); - // Sort by time to get a true order of the operations (between tables) - const sorted = flatten(allMutsOnTables).sort((a, b) => a.mut.txid === b.mut.txid - ? a.mut.opNo - b.mut.opNo // Within same transaction, sort by opNo - : a.mut.ts - b.mut.ts // Different transactions - sort by timestamp when mutation resolved - ); - const result = []; - let currentEntry = null; - let currentTxid = null; - for (const { table, mut } of sorted) { - if (currentEntry && - currentEntry.table === table && - currentTxid === mut.txid) { - currentEntry.muts.push(mut); - } - else { - currentEntry = { - table, - muts: [mut], - }; - currentTxid = mut.txid; - result.push(currentEntry); - } - } - // Filter out those tables that doesn't have any mutations: - return result; - }); -} - -function randomString(bytes) { - const buf = new Uint8Array(bytes); - if (typeof crypto !== 'undefined') { - crypto.getRandomValues(buf); - } - else { - for (let i = 0; i < bytes; i++) - buf[i] = Math.floor(Math.random() * 256); - } - if (typeof Buffer !== 'undefined' && Buffer.from) { - return Buffer.from(buf).toString('base64'); - } - else if (typeof btoa !== 'undefined') { - return btoa(String.fromCharCode.apply(null, buf)); - } - else { - throw new Error('No btoa or Buffer available'); - } -} - -function listSyncifiedChanges(tablesToSyncify, currentUser, schema, alreadySyncedRealms) { - return __awaiter(this, void 0, void 0, function* () { - const txid = `upload-${randomString(8)}`; - if (currentUser.isLoggedIn) { - if (tablesToSyncify.length > 0) { - const ignoredRealms = new Set(alreadySyncedRealms || []); - const upserts = yield Promise.all(tablesToSyncify.map((table) => __awaiter(this, void 0, void 0, function* () { - const { extractKey } = table.core.schema.primaryKey; - if (!extractKey) - return { table: table.name, muts: [] }; // Outbound tables are not synced. - const dexieCloudTableSchema = schema[table.name]; - const query = (dexieCloudTableSchema === null || dexieCloudTableSchema === void 0 ? void 0 : dexieCloudTableSchema.generatedGlobalId) - ? table.filter((item) => { - extractKey(item); - return (!ignoredRealms.has(item.realmId || '') && - //(id[0] !== '#' || !!item.$ts) && // Private obj need no sync if not changed - isValidAtID(extractKey(item), dexieCloudTableSchema === null || dexieCloudTableSchema === void 0 ? void 0 : dexieCloudTableSchema.idPrefix)); - }) - : table.filter((item) => { - const id = extractKey(item); - return (!ignoredRealms.has(item.realmId || '') && - //(id[0] !== '#' || !!item.$ts) && // Private obj need no sync if not changed - isValidSyncableID(id)); - }); - const unsyncedObjects = yield query.toArray(); - if (unsyncedObjects.length > 0) { - const mut = { - type: 'upsert', - values: unsyncedObjects, - keys: unsyncedObjects.map(extractKey), - userId: currentUser.userId, - txid, - }; - return { - table: table.name, - muts: [mut], - }; - } - else { - return { - table: table.name, - muts: [], - }; - } - }))); - return upserts.filter((op) => op.muts.length > 0); - } - } - return []; - }); -} - -function getTablesToSyncify(db, syncState) { - const syncedTables = (syncState === null || syncState === void 0 ? void 0 : syncState.syncedTables) || []; - const syncableTables = getSyncableTables(db); - const tablesToSyncify = syncableTables.filter((tbl) => !syncedTables.includes(tbl.name)); - return tablesToSyncify; -} - -const { toString: toStr } = {}; -function getToStringTag(val) { - return toStr.call(val).slice(8, -1); -} -function escapeDollarProps(value) { - const keys = Object.keys(value); - let dollarKeys = null; - for (let i = 0, l = keys.length; i < l; ++i) { - if (keys[i][0] === "$") { - dollarKeys = dollarKeys || []; - dollarKeys.push(keys[i]); - } - } - if (!dollarKeys) - return value; - const clone = { ...value }; - for (const k of dollarKeys) { - delete clone[k]; - } - for (const k of dollarKeys) { - clone["$" + k] = value[k]; - } - return clone; -} -const ObjectDef = { - replace: escapeDollarProps, -}; -function TypesonSimplified(...typeDefsInputs) { - const typeDefs = typeDefsInputs.reduce((p, c) => ({ ...p, ...c }), typeDefsInputs.reduce((p, c) => ({ ...c, ...p }), {})); - const protoMap = new WeakMap(); - return { - stringify(value, alternateChannel, space) { - const json = JSON.stringify(value, function (key) { - const realVal = this[key]; - const typeDef = getTypeDef(realVal); - return typeDef - ? typeDef.replace(realVal, alternateChannel, typeDefs) - : realVal; - }, space); - return json; - }, - parse(tson, alternateChannel) { - const stack = []; - return JSON.parse(tson, function (key, value) { - // - // Parent Part - // - const type = value === null || value === void 0 ? void 0 : value.$t; - if (type) { - const typeDef = typeDefs[type]; - value = typeDef - ? typeDef.revive(value, alternateChannel, typeDefs) - : value; - } - let top = stack[stack.length - 1]; - if (top && top[0] === value) { - // Do what the kid told us to - // Unescape dollar props - value = { ...value }; - // Delete keys that children wanted us to delete - for (const k of top[1]) - delete value[k]; - // Set keys that children wanted us to set - for (const [k, v] of Object.entries(top[2])) { - value[k] = v; - } - stack.pop(); - } - // - // Child part - // - if (value === undefined || (key[0] === "$" && key !== "$t")) { - top = stack[stack.length - 1]; - let deletes; - let mods; - if (top && top[0] === this) { - deletes = top[1]; - mods = top[2]; - } - else { - stack.push([this, (deletes = []), (mods = {})]); - } - if (key[0] === "$" && key !== "$t") { - // Unescape props (also preserves undefined if this is a combo) - deletes.push(key); - mods[key.substr(1)] = value; - } - else { - // Preserve undefined - mods[key] = undefined; - } - } - return value; - }); - }, - }; - function getTypeDef(realVal) { - const type = typeof realVal; - switch (typeof realVal) { - case "object": - case "function": { - // "object", "function", null - if (realVal === null) - return null; - const proto = Object.getPrototypeOf(realVal); - if (!proto) - return ObjectDef; - let typeDef = protoMap.get(proto); - if (typeDef !== undefined) - return typeDef; // Null counts to! So the caching of Array.prototype also counts. - const toStringTag = getToStringTag(realVal); - const entry = Object.entries(typeDefs).find(([typeName, typeDef]) => { var _a, _b; return (_b = (_a = typeDef === null || typeDef === void 0 ? void 0 : typeDef.test) === null || _a === void 0 ? void 0 : _a.call(typeDef, realVal, toStringTag)) !== null && _b !== void 0 ? _b : typeName === toStringTag; }); - typeDef = entry === null || entry === void 0 ? void 0 : entry[1]; - if (!typeDef) { - typeDef = Array.isArray(realVal) - ? null - : typeof realVal === "function" - ? typeDefs.function || null - : ObjectDef; - } - protoMap.set(proto, typeDef); - return typeDef; - } - default: - return typeDefs[type]; - } - } -} - -const BisonBinaryTypes = { - Blob: { - test: (blob, toStringTag) => toStringTag === "Blob", - replace: (blob, altChannel) => { - const i = altChannel.length; - altChannel.push(blob); - return { - $t: "Blob", - mimeType: blob.type, - i, - }; - }, - revive: ({ i, mimeType }, altChannel) => new Blob([altChannel[i]], { type: mimeType }), - }, -}; - -var numberDef = { - number: { - replace: (num) => { - switch (true) { - case isNaN(num): - return { $t: "number", v: "NaN" }; - case num === Infinity: - return { $t: "number", v: "Infinity" }; - case num === -Infinity: - return { $t: "number", v: "-Infinity" }; - default: - return num; - } - }, - revive: ({ v }) => Number(v), - }, -}; - -const bigIntDef = { - bigint: { - replace: (realVal) => { - return { $t: "bigint", v: "" + realVal }; - }, - revive: (obj) => BigInt(obj.v), - }, -}; - -var DateDef = { - Date: { - replace: (date) => ({ - $t: "Date", - v: isNaN(date.getTime()) ? "NaN" : date.toISOString(), - }), - revive: ({ v }) => new Date(v === "NaN" ? NaN : Date.parse(v)), - }, -}; - -var SetDef = { - Set: { - replace: (set) => ({ - $t: "Set", - v: Array.from(set.entries()), - }), - revive: ({ v }) => new Set(v), - }, -}; - -var MapDef = { - Map: { - replace: (map) => ({ - $t: "Map", - v: Array.from(map.entries()), - }), - revive: ({ v }) => new Map(v), - }, -}; - -const _global = typeof globalThis !== "undefined" // All modern environments (node, bun, deno, browser, workers, webview etc) - ? globalThis - : typeof self !== "undefined" // Older browsers, workers, webview, window etc - ? self - : typeof global !== "undefined" // Older versions of node - ? global - : undefined; // Unsupported environment. No idea to return 'this' since we are in a module or a function scope anyway. - -var TypedArraysDefs = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "DataView", - "BigInt64Array", - "BigUint64Array", -].reduce((specs, typeName) => ({ - ...specs, - [typeName]: { - // Replace passes the the typed array into $t, buffer so that - // the ArrayBuffer typedef takes care of further handling of the buffer: - // {$t:"Uint8Array",buffer:{$t:"ArrayBuffer",idx:0}} - // CHANGED ABOVE! Now shortcutting that for more sparse format of the typed arrays - // to contain the b64 property directly. - replace: (a, _, typeDefs) => { - const result = { - $t: typeName, - v: typeDefs.ArrayBuffer.replace(a.byteOffset === 0 && a.byteLength === a.buffer.byteLength - ? a.buffer - : a.buffer.slice(a.byteOffset, a.byteOffset + a.byteLength), _, typeDefs).v, - }; - return result; - }, - revive: ({ v }, _, typeDefs) => { - const TypedArray = _global[typeName]; - return (TypedArray && - new TypedArray(typeDefs.ArrayBuffer.revive({ v }, _, typeDefs))); - }, - }, -}), {}); - -function b64LexEncode(b) { - return b64ToLex(b64encode(b)); -} -function b64LexDecode(b64Lex) { - return b64decode(lexToB64(b64Lex)); -} -function b64ToLex(base64) { - var encoded = ""; - for (var i = 0, length = base64.length; i < length; i++) { - encoded += ENCODE_TABLE[base64[i]]; - } - return encoded; -} -function lexToB64(base64lex) { - // only accept string input - if (typeof base64lex !== "string") { - throw new Error("invalid decoder input: " + base64lex); - } - var base64 = ""; - for (var i = 0, length = base64lex.length; i < length; i++) { - base64 += DECODE_TABLE[base64lex[i]]; - } - return base64; -} -const DECODE_TABLE = { - "-": "=", - "0": "A", - "1": "B", - "2": "C", - "3": "D", - "4": "E", - "5": "F", - "6": "G", - "7": "H", - "8": "I", - "9": "J", - A: "K", - B: "L", - C: "M", - D: "N", - E: "O", - F: "P", - G: "Q", - H: "R", - I: "S", - J: "T", - K: "U", - L: "V", - M: "W", - N: "X", - O: "Y", - P: "Z", - Q: "a", - R: "b", - S: "c", - T: "d", - U: "e", - V: "f", - W: "g", - X: "h", - Y: "i", - Z: "j", - _: "k", - a: "l", - b: "m", - c: "n", - d: "o", - e: "p", - f: "q", - g: "r", - h: "s", - i: "t", - j: "u", - k: "v", - l: "w", - m: "x", - n: "y", - o: "z", - p: "0", - q: "1", - r: "2", - s: "3", - t: "4", - u: "5", - v: "6", - w: "7", - x: "8", - y: "9", - z: "+", - "|": "/", -}; -const ENCODE_TABLE = {}; -for (const c of Object.keys(DECODE_TABLE)) { - ENCODE_TABLE[DECODE_TABLE[c]] = c; -} - -var ArrayBufferDef = { - ArrayBuffer: { - replace: (ab) => ({ - $t: "ArrayBuffer", - v: b64LexEncode(ab), - }), - revive: ({ v }) => { - const ba = b64LexDecode(v); - return ba.buffer.byteLength === ba.byteLength - ? ba.buffer - : ba.buffer.slice(ba.byteOffset, ba.byteOffset + ba.byteLength); - }, - }, -}; - -class FakeBlob { - constructor(buf, type) { - this.buf = buf; - this.type = type; - } -} - -function readBlobSync(b) { - const req = new XMLHttpRequest(); - req.overrideMimeType("text/plain; charset=x-user-defined"); - req.open("GET", URL.createObjectURL(b), false); // Sync - req.send(); - if (req.status !== 200 && req.status !== 0) { - throw new Error("Bad Blob access: " + req.status); - } - return req.responseText; -} - -function string2ArrayBuffer(str) { - const array = new Uint8Array(str.length); - for (let i = 0; i < str.length; ++i) { - array[i] = str.charCodeAt(i); // & 0xff; - } - return array.buffer; -} - -var BlobDef = { - Blob: { - test: (blob, toStringTag) => toStringTag === "Blob" || blob instanceof FakeBlob, - replace: (blob) => ({ - $t: "Blob", - v: blob instanceof FakeBlob - ? b64encode(blob.buf) - : b64encode(string2ArrayBuffer(readBlobSync(blob))), - type: blob.type, - }), - revive: ({ type, v }) => { - const ab = b64decode(v); - return typeof Blob !== undefined - ? new Blob([ab]) - : new FakeBlob(ab.buffer, type); - }, - }, -}; - -const builtin = { - ...numberDef, - ...bigIntDef, - ...DateDef, - ...SetDef, - ...MapDef, - ...TypedArraysDefs, - ...ArrayBufferDef, - ...BlobDef, // Should be moved to another preset for DOM types (or universal? since it supports node as well with FakeBlob) -}; - -function Bison(...typeDefsInputs) { - const tson = TypesonSimplified(builtin, BisonBinaryTypes, ...typeDefsInputs); - return { - toBinary(value) { - const [blob, json] = this.stringify(value); - const lenBuf = new ArrayBuffer(4); - new DataView(lenBuf).setUint32(0, blob.size); - return new Blob([lenBuf, blob, json]); - }, - stringify(value) { - const binaries = []; - const json = tson.stringify(value, binaries); - const blob = new Blob(binaries.map((b) => { - const lenBuf = new ArrayBuffer(4); - new DataView(lenBuf).setUint32(0, "byteLength" in b ? b.byteLength : b.size); - return new Blob([lenBuf, b]); - })); - return [blob, json]; - }, - async parse(json, binData) { - let pos = 0; - const arrayBuffers = []; - const buf = await readBlobBinary(binData); - const view = new DataView(buf); - while (pos < buf.byteLength) { - const len = view.getUint32(pos); - pos += 4; - const ab = buf.slice(pos, pos + len); - pos += len; - arrayBuffers.push(ab); - } - return tson.parse(json, arrayBuffers); - }, - async fromBinary(blob) { - const len = new DataView(await readBlobBinary(blob.slice(0, 4))).getUint32(0); - const binData = blob.slice(4, len + 4); - const json = await readBlob(blob.slice(len + 4)); - return await this.parse(json, binData); - }, - }; -} -function readBlob(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onabort = (ev) => reject(new Error("file read aborted")); - reader.onerror = (ev) => reject(ev.target.error); - reader.onload = (ev) => resolve(ev.target.result); - reader.readAsText(blob); - }); -} -function readBlobBinary(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onabort = (ev) => reject(new Error("file read aborted")); - reader.onerror = (ev) => reject(ev.target.error); - reader.onload = (ev) => resolve(ev.target.result); - reader.readAsArrayBuffer(blob); - }); -} - -/** The undefined type is not part of builtin but can be manually added. - * The reason for supporting undefined is if the following object should be revived correctly: - * - * {foo: undefined} - * - * Without including this typedef, the revived object would just be {}. - * If including this typedef, the revived object would be {foo: undefined}. - */ -var undefinedDef = { - undefined: { - replace: () => ({ - $t: "undefined" - }), - revive: () => undefined, - }, -}; - -// Since server revisions are stored in bigints, we need to handle clients without -// bigint support to not fail when serverRevision is passed over to client. -// We need to not fail when reviving it and we need to somehow store the information. -// Since the revived version will later on be put into indexedDB we have another -// issue: When reading it back from indexedDB we will get a poco object that we -// cannot replace correctly when sending it to server. So we will also need -// to do an explicit workaround in the protocol where a bigint is supported. -// The workaround should be there regardless if browser supports BigInt or not, because -// the serverRev might have been stored in IDB before the browser was upgraded to support bigint. -// -// if (typeof serverRev.rev !== "bigint") -// if (hasBigIntSupport) -// serverRev.rev = bigIntDef.bigint.revive(server.rev) -// else -// serverRev.rev = new FakeBigInt(server.rev) -const hasBigIntSupport = typeof BigInt === 'function' && typeof BigInt(0) === 'bigint'; -class FakeBigInt { - toString() { - return this.v; - } - constructor(value) { - this.v = value; - } -} -const defs = Object.assign(Object.assign(Object.assign({}, undefinedDef), (hasBigIntSupport - ? {} - : { - bigint: { - test: (val) => val instanceof FakeBigInt, - replace: (fakeBigInt) => { - return Object.assign({ $t: 'bigint' }, fakeBigInt); - }, - revive: ({ v, }) => new FakeBigInt(v) - } - })), { PropModification: { - test: (val) => val instanceof dexie__WEBPACK_IMPORTED_MODULE_0__.PropModification, - replace: (propModification) => { - return Object.assign({ $t: 'PropModification' }, propModification); - }, - revive: (_a) => { - var propModification = __rest(_a, ["$t"]); - return new dexie__WEBPACK_IMPORTED_MODULE_0__.PropModification(propModification); - } - } }); -const TSON = TypesonSimplified(builtin, defs); -const BISON = Bison(defs); - -function encodeIdsForServer(schema, currentUser, changes) { - const rv = []; - for (let change of changes) { - const { table, muts } = change; - const tableSchema = schema.tables.find((t) => t.name === table); - if (!tableSchema) - throw new Error(`Internal error: table ${table} not found in DBCore schema`); - const { primaryKey } = tableSchema; - let changeClone = change; - muts.forEach((mut, mutIndex) => { - const rewriteValues = !primaryKey.outbound && - (mut.type === 'upsert' || mut.type === 'insert'); - mut.keys.forEach((key, keyIndex) => { - if (Array.isArray(key)) { - // Server only support string keys. Dexie Cloud client support strings or array of strings. - if (changeClone === change) - changeClone = cloneChange(change, rewriteValues); - const mutClone = changeClone.muts[mutIndex]; - const rewrittenKey = JSON.stringify(key); - mutClone.keys[keyIndex] = rewrittenKey; - /* Bug (#1777) - We should not rewrite values. It will fail because the key is array and the value is string. - Only the keys should be rewritten and it's already done on the server. - We should take another round of revieweing how key transformations are being done between - client and server and let the server do the key transformations entirely instead now that - we have the primary key schema on the server making it possible to do so. - if (rewriteValues) { - Dexie.setByKeyPath( - (mutClone as DBInsertOperation).values[keyIndex], - primaryKey.keyPath!, - rewrittenKey - ); - }*/ - } - else if (key[0] === '#') { - // Private ID - translate! - if (changeClone === change) - changeClone = cloneChange(change, rewriteValues); - const mutClone = changeClone.muts[mutIndex]; - if (!currentUser.isLoggedIn) - throw new Error(`Internal error: Cannot sync private IDs before authenticated`); - const rewrittenKey = `${key}:${currentUser.userId}`; - mutClone.keys[keyIndex] = rewrittenKey; - if (rewriteValues) { - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].setByKeyPath(mutClone.values[keyIndex], primaryKey.keyPath, rewrittenKey); - } - } - }); - }); - rv.push(changeClone); - } - return rv; -} -function cloneChange(change, rewriteValues) { - // clone on demand: - return Object.assign(Object.assign({}, change), { muts: rewriteValues - ? change.muts.map((m) => { - return (m.type === 'insert' || m.type === 'upsert') && m.values - ? Object.assign(Object.assign({}, m), { keys: m.keys.slice(), values: m.values.slice() }) : Object.assign(Object.assign({}, m), { keys: m.keys.slice() }); - }) - : change.muts.map((m) => (Object.assign(Object.assign({}, m), { keys: m.keys.slice() }))) }); -} - -// If we get Ratelimit-Limit and Ratelimit-Remaining where Ratelimit-Remaining is below -// (Ratelimit-Limit / 2), we should delay the next sync by (Ratelimit-Reset / Ratelimit-Remaining) -// seconds (given that there is a Ratelimit-Reset header). -let syncRatelimitDelays = new WeakMap(); -function checkSyncRateLimitDelay(db) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const delatMilliseconds = ((_b = (_a = syncRatelimitDelays.get(db)) === null || _a === void 0 ? void 0 : _a.getTime()) !== null && _b !== void 0 ? _b : 0) - Date.now(); - if (delatMilliseconds > 0) { - console.debug(`Stalling sync request ${delatMilliseconds} ms to spare ratelimits`); - yield new Promise(resolve => setTimeout(resolve, delatMilliseconds)); - } - }); -} -function updateSyncRateLimitDelays(db, res) { - const limit = res.headers.get('Ratelimit-Limit'); - const remaining = res.headers.get('Ratelimit-Remaining'); - const reset = res.headers.get('Ratelimit-Reset'); - if (limit && remaining && reset) { - const limitNum = Number(limit); - const remainingNum = Math.max(0, Number(remaining)); - const willResetInSeconds = Number(reset); - if (remainingNum < limitNum / 2) { - const delay = Math.ceil(willResetInSeconds / (remainingNum + 1)); - syncRatelimitDelays.set(db, new Date(Date.now() + delay * 1000)); - console.debug(`Sync ratelimit delay set to ${delay} seconds`); - } - else { - syncRatelimitDelays.delete(db); - console.debug(`Sync ratelimit delay cleared`); - } - } -} - -//import {BisonWebStreamReader} from "dreambase-library/dist/typeson-simplified/BisonWebStreamReader"; -function syncWithServer(changes, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser) { - return __awaiter(this, void 0, void 0, function* () { - // - // Push changes to server using fetch - // - const headers = { - Accept: 'application/json, application/x-bison, application/x-bison-stream', - 'Content-Type': 'application/tson', - }; - const updatedUser = yield loadAccessToken(db); - /* - if (updatedUser?.license && changes.length > 0) { - if (updatedUser.license.status === 'expired') { - throw new Error(`License has expired`); - } - if (updatedUser.license.status === 'deactivated') { - throw new Error(`License deactivated`); - } - } - */ - const accessToken = updatedUser === null || updatedUser === void 0 ? void 0 : updatedUser.accessToken; - if (accessToken) { - headers.Authorization = `Bearer ${accessToken}`; - } - const syncRequest = { - v: 2, - dbID: syncState === null || syncState === void 0 ? void 0 : syncState.remoteDbId, - clientIdentity, - schema: schema || {}, - lastPull: syncState - ? { - serverRevision: syncState.serverRevision, - realms: syncState.realms, - inviteRealms: syncState.inviteRealms, - } - : undefined, - baseRevs, - changes: encodeIdsForServer(db.dx.core.schema, currentUser, changes), - }; - console.debug('Sync request', syncRequest); - db.syncStateChangedEvent.next({ - phase: 'pushing', - }); - const res = yield fetch(`${databaseUrl}/sync`, { - method: 'post', - headers, - credentials: 'include', // For Arr Affinity cookie only, for better Rate-Limit counting only. - body: TSON.stringify(syncRequest), - }); - //const contentLength = Number(res.headers.get('content-length')); - db.syncStateChangedEvent.next({ - phase: 'pulling', - }); - updateSyncRateLimitDelays(db, res); - if (!res.ok) { - throw new HttpError(res); - } - switch (res.headers.get('content-type')) { - case 'application/x-bison': - return BISON.fromBinary(yield res.blob()); - case 'application/x-bison-stream': //return BisonWebStreamReader(BISON, res); - default: - case 'application/json': { - const text = yield res.text(); - const syncRes = TSON.parse(text); - return syncRes; - } - } - }); -} - -function modifyLocalObjectsWithNewUserId(syncifiedTables, currentUser, alreadySyncedRealms) { - return __awaiter(this, void 0, void 0, function* () { - const ignoredRealms = new Set(alreadySyncedRealms || []); - for (const table of syncifiedTables) { - if (table.name === "members") { - // members - yield table.toCollection().modify((member) => { - if (!ignoredRealms.has(member.realmId) && (!member.userId || member.userId === UNAUTHORIZED_USER.userId)) { - member.userId = currentUser.userId; - } - }); - } - else if (table.name === "roles") ; - else if (table.name === "realms") { - // realms - yield table.toCollection().modify((realm) => { - if (!ignoredRealms.has(realm.realmId) && (realm.owner === undefined || realm.owner === UNAUTHORIZED_USER.userId)) { - realm.owner = currentUser.userId; - } - }); - } - else { - // application entities - yield table.toCollection().modify((obj) => { - if (!obj.realmId || !ignoredRealms.has(obj.realmId)) { - if (!obj.owner || obj.owner === UNAUTHORIZED_USER.userId) - obj.owner = currentUser.userId; - if (!obj.realmId || obj.realmId === UNAUTHORIZED_USER.userId) { - obj.realmId = currentUser.userId; - } - } - }); - } - } - }); -} - -function throwIfCancelled(cancelToken) { - if (cancelToken === null || cancelToken === void 0 ? void 0 : cancelToken.cancelled) - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].AbortError(`Operation was cancelled`); -} - -/* Need this because navigator.onLine seems to say "false" when it is actually online. - This function relies initially on navigator.onLine but then uses online and offline events - which seem to be more reliable. -*/ -let isOnline = false; -if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { - isOnline = navigator.onLine; - self.addEventListener('online', () => isOnline = true); - self.addEventListener('offline', () => isOnline = false); -} - -function updateBaseRevs(db, schema, latestRevisions, serverRev) { - return __awaiter(this, void 0, void 0, function* () { - yield db.$baseRevs.bulkPut(Object.keys(schema) - .filter((table) => schema[table].markedForSync) - .map((tableName) => { - const lastClientRevOnPreviousServerRev = latestRevisions[tableName] || 0; - return { - tableName, - clientRev: lastClientRevOnPreviousServerRev + 1, - serverRev, - }; - })); - }); -} - -function getLatestRevisionsPerTable(clientChangeSet, lastRevisions = {}) { - for (const { table, muts } of clientChangeSet) { - const lastRev = muts.length > 0 ? muts[muts.length - 1].rev : null; - lastRevisions[table] = lastRev || lastRevisions[table] || 0; - } - return lastRevisions; -} - -function bulkUpdate(table, keys, changeSpecs) { - return __awaiter(this, void 0, void 0, function* () { - const objs = yield table.bulkGet(keys); - const resultKeys = []; - const resultObjs = []; - keys.forEach((key, idx) => { - const obj = objs[idx]; - if (obj) { - for (const [keyPath, value] of Object.entries(changeSpecs[idx])) { - if (keyPath === table.schema.primKey.keyPath) { - if ((0,dexie__WEBPACK_IMPORTED_MODULE_0__.cmp)(value, key) !== 0) { - throw new Error(`Cannot change primary key`); - } - } - else { - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].setByKeyPath(obj, keyPath, value); - } - } - resultKeys.push(key); - resultObjs.push(obj); - } - }); - yield (table.schema.primKey.keyPath == null - ? table.bulkPut(resultObjs, resultKeys) - : table.bulkPut(resultObjs)); - }); -} - -function applyServerChanges(changes, db) { - return __awaiter(this, void 0, void 0, function* () { - console.debug('Applying server changes', changes, dexie__WEBPACK_IMPORTED_MODULE_0__["default"].currentTransaction); - for (const { table: tableName, muts } of changes) { - const table = db.table(tableName); - if (!table) - continue; // If server sends changes on a table we don't have, ignore it. - const { primaryKey } = table.core.schema; - const keyDecoder = (key) => { - switch (key[0]) { - case '[': - // Decode JSON array - if (key.endsWith(']')) - try { - // On server, array keys are transformed to JSON string representation - return JSON.parse(key); - } - catch (_a) { } - return key; - case '#': - // Decode private ID (do the opposite from what's done in encodeIdsForServer()) - if (key.endsWith(':' + db.cloud.currentUserId)) { - return key.substr(0, key.length - db.cloud.currentUserId.length - 1); - } - return key; - default: - return key; - } - }; - for (const mut of muts) { - const keys = mut.keys.map(keyDecoder); - switch (mut.type) { - case 'insert': - if (primaryKey.outbound) { - yield table.bulkAdd(mut.values, keys); - } - else { - keys.forEach((key, i) => { - // Make sure inbound keys are consistent - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].setByKeyPath(mut.values[i], primaryKey.keyPath, key); - }); - yield table.bulkAdd(mut.values); - } - break; - case 'upsert': - if (primaryKey.outbound) { - yield table.bulkPut(mut.values, keys); - } - else { - keys.forEach((key, i) => { - // Make sure inbound keys are consistent - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].setByKeyPath(mut.values[i], primaryKey.keyPath, key); - }); - yield table.bulkPut(mut.values); - } - break; - case 'modify': - if (keys.length === 1) { - yield table.update(keys[0], mut.changeSpec); - } - else { - yield table.where(':id').anyOf(keys).modify(mut.changeSpec); - } - break; - case 'update': - yield bulkUpdate(table, keys, mut.changeSpecs); - break; - case 'delete': - yield table.bulkDelete(keys); - break; - } - } - } - }); -} - -const CURRENT_SYNC_WORKER = 'currentSyncWorker'; -function sync(db, options, schema, syncOptions) { - return _sync - .apply(this, arguments) - .then((result) => { - if (!(syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.justCheckIfNeeded)) { // && syncOptions?.purpose !== 'push') { - db.syncStateChangedEvent.next({ - phase: 'in-sync', - }); - } - return result; - }) - .catch((error) => __awaiter(this, void 0, void 0, function* () { - if (syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.justCheckIfNeeded) - return Promise.reject(error); // Just rethrow. - console.debug('Error from _sync', { - isOnline, - syncOptions, - error, - }); - if (isOnline && - (syncOptions === null || syncOptions === void 0 ? void 0 : syncOptions.retryImmediatelyOnFetchError) && - (error === null || error === void 0 ? void 0 : error.name) === 'TypeError' && - /fetch/.test(error === null || error === void 0 ? void 0 : error.message)) { - db.syncStateChangedEvent.next({ - phase: 'error', - error, - }); - // Retry again in 500 ms but if it fails again, don't retry. - yield new Promise((resolve) => setTimeout(resolve, 500)); - return yield sync(db, options, schema, Object.assign(Object.assign({}, syncOptions), { retryImmediatelyOnFetchError: false })); - } - // Make sure that no matter whether sync() explodes or not, - // always update the timestamp. Also store the error. - yield db.$syncState.update('syncState', { - timestamp: new Date(), - error: '' + error, - }); - db.syncStateChangedEvent.next({ - phase: isOnline ? 'error' : 'offline', - error: new Error('' + (error === null || error === void 0 ? void 0 : error.message) || error), - }); - return Promise.reject(error); - })); -} -function _sync(db, options, schema, { isInitialSync, cancelToken, justCheckIfNeeded, purpose } = { - isInitialSync: false, -}) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (!justCheckIfNeeded) { - console.debug('SYNC STARTED', { isInitialSync, purpose }); - } - if (!((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.databaseUrl)) - throw new Error(`Internal error: sync must not be called when no databaseUrl is configured`); - const { databaseUrl } = options; - const currentUser = yield db.getCurrentUser(); // Keep same value across entire sync flow: - const tablesToSync = currentUser.isLoggedIn ? getSyncableTables(db) : []; - const mutationTables = tablesToSync.map((tbl) => db.table(getMutationTable(tbl.name))); - // If this is not the initial sync, - // go through tables that were previously not synced but should now be according to - // logged in state and the sync table whitelist in db.cloud.options. - // - // Prepare for syncification by modifying locally unauthorized objects: - // - const persistedSyncState = yield db.getPersistedSyncState(); - const readyForSyncification = !isInitialSync && currentUser.isLoggedIn; - const tablesToSyncify = readyForSyncification - ? getTablesToSyncify(db, persistedSyncState) - : []; - throwIfCancelled(cancelToken); - const doSyncify = tablesToSyncify.length > 0; - if (doSyncify) { - if (justCheckIfNeeded) - return true; - //console.debug('sync doSyncify is true'); - yield db.transaction('rw', tablesToSyncify, (tx) => __awaiter(this, void 0, void 0, function* () { - // @ts-ignore - tx.idbtrans.disableChangeTracking = true; - // @ts-ignore - tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware! - yield modifyLocalObjectsWithNewUserId(tablesToSyncify, currentUser, persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.realms); - })); - throwIfCancelled(cancelToken); - } - // - // List changes to sync - // - const [clientChangeSet, syncState, baseRevs] = yield db.transaction('r', db.tables, () => __awaiter(this, void 0, void 0, function* () { - const syncState = yield db.getPersistedSyncState(); - const baseRevs = yield db.$baseRevs.toArray(); - let clientChanges = yield listClientChanges(mutationTables); - throwIfCancelled(cancelToken); - if (doSyncify) { - const alreadySyncedRealms = [ - ...((persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.realms) || []), - ...((persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.inviteRealms) || []), - ]; - const syncificationInserts = yield listSyncifiedChanges(tablesToSyncify, currentUser, schema, alreadySyncedRealms); - throwIfCancelled(cancelToken); - clientChanges = clientChanges.concat(syncificationInserts); - return [clientChanges, syncState, baseRevs]; - } - return [clientChanges, syncState, baseRevs]; - })); - const pushSyncIsNeeded = clientChangeSet.some((set) => set.muts.some((mut) => mut.keys.length > 0)); - if (justCheckIfNeeded) { - console.debug('Sync is needed:', pushSyncIsNeeded); - return pushSyncIsNeeded; - } - if (purpose === 'push' && !pushSyncIsNeeded) { - // The purpose of this request was to push changes - return false; - } - const latestRevisions = getLatestRevisionsPerTable(clientChangeSet, syncState === null || syncState === void 0 ? void 0 : syncState.latestRevisions); - const clientIdentity = (syncState === null || syncState === void 0 ? void 0 : syncState.clientIdentity) || randomString$1(16); - // - // Push changes to server - // - throwIfCancelled(cancelToken); - const res = yield syncWithServer(clientChangeSet, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser); - console.debug('Sync response', res); - // - // Apply changes locally and clear old change entries: - // - const done = yield db.transaction('rw', db.tables, (tx) => __awaiter(this, void 0, void 0, function* () { - // @ts-ignore - tx.idbtrans.disableChangeTracking = true; - // @ts-ignore - tx.idbtrans.disableAccessControl = true; // TODO: Take care of this flag in access control middleware! - // Update db.cloud.schema from server response. - // Local schema MAY include a subset of tables, so do not force all tables into local schema. - for (const tableName of Object.keys(schema)) { - if (res.schema[tableName]) { - // Write directly into configured schema. This code can only be executed alone. - schema[tableName] = res.schema[tableName]; - } - } - yield db.$syncState.put(schema, 'schema'); - // List mutations that happened during our exchange with the server: - const addedClientChanges = yield listClientChanges(mutationTables, db, { - since: latestRevisions, - }); - // - // Delete changes now as server has return success - // (but keep changes that haven't reached server yet) - // - for (const mutTable of mutationTables) { - const tableName = getTableFromMutationTable(mutTable.name); - if (!addedClientChanges.some((ch) => ch.table === tableName && ch.muts.length > 0)) { - // No added mutations for this table during the time we sent changes - // to the server. - // It is therefore safe to clear all changes (which is faster than - // deleting a range) - yield Promise.all([ - mutTable.clear(), - db.$baseRevs.where({ tableName }).delete(), - ]); - } - else if (latestRevisions[tableName]) { - const latestRev = latestRevisions[tableName] || 0; - yield Promise.all([ - mutTable.where('rev').belowOrEqual(latestRev).delete(), - db.$baseRevs - .where(':id') - .between([tableName, -Infinity], [tableName, latestRev + 1], true, true) - .reverse() - .offset(1) // Keep one entry (the one mapping muts that came during fetch --> previous server revision) - .delete(), - ]); - } - else ; - } - // Update latestRevisions object according to additional changes: - getLatestRevisionsPerTable(addedClientChanges, latestRevisions); - // Update/add new entries into baseRevs map. - // * On tables without mutations since last serverRevision, - // this will update existing entry. - // * On tables where mutations have been recorded since last - // serverRevision, this will create a new entry. - // The purpose of this operation is to mark a start revision (per table) - // so that all client-mutations that come after this, will be mapped to current - // server revision. - yield updateBaseRevs(db, schema, latestRevisions, res.serverRevision); - const syncState = yield db.getPersistedSyncState(); - // - // Delete objects from removed realms - // - yield deleteObjectsFromRemovedRealms(db, res, syncState); - // - // Update syncState - // - const newSyncState = syncState || { - syncedTables: [], - latestRevisions: {}, - realms: [], - inviteRealms: [], - clientIdentity, - }; - if (readyForSyncification) { - newSyncState.syncedTables = tablesToSync - .map((tbl) => tbl.name) - .concat(tablesToSyncify.map((tbl) => tbl.name)); - } - newSyncState.latestRevisions = latestRevisions; - newSyncState.remoteDbId = res.dbId; - newSyncState.initiallySynced = true; - newSyncState.realms = res.realms; - newSyncState.inviteRealms = res.inviteRealms; - newSyncState.serverRevision = res.serverRevision; - newSyncState.timestamp = new Date(); - delete newSyncState.error; - const filteredChanges = filterServerChangesThroughAddedClientChanges(res.changes, addedClientChanges); - // - // apply server changes - // - yield applyServerChanges(filteredChanges, db); - // - // Update syncState - // - db.$syncState.put(newSyncState, 'syncState'); - return addedClientChanges.length === 0; - })); - if (!done) { - console.debug('MORE SYNC NEEDED. Go for it again!'); - yield checkSyncRateLimitDelay(db); - return yield _sync(db, options, schema, { isInitialSync, cancelToken }); - } - console.debug('SYNC DONE', { isInitialSync }); - db.syncCompleteEvent.next(); - return false; // Not needed anymore - }); -} -function deleteObjectsFromRemovedRealms(db, res, prevState) { - return __awaiter(this, void 0, void 0, function* () { - const deletedRealms = new Set(); - const rejectedRealms = new Set(); - const previousRealmSet = prevState ? prevState.realms : []; - const previousInviteRealmSet = prevState ? prevState.inviteRealms : []; - const updatedRealmSet = new Set(res.realms); - const updatedTotalRealmSet = new Set(res.realms.concat(res.inviteRealms)); - for (const realmId of previousRealmSet) { - if (!updatedRealmSet.has(realmId)) { - rejectedRealms.add(realmId); - if (!updatedTotalRealmSet.has(realmId)) { - deletedRealms.add(realmId); - } - } - } - for (const realmId of previousInviteRealmSet.concat(previousRealmSet)) { - if (!updatedTotalRealmSet.has(realmId)) { - deletedRealms.add(realmId); - } - } - if (deletedRealms.size > 0 || rejectedRealms.size > 0) { - const tables = getSyncableTables(db); - for (const table of tables) { - let realmsToDelete = ['realms', 'members', 'roles'].includes(table.name) - ? deletedRealms // These tables should spare rejected ones. - : rejectedRealms; // All other tables shoudl delete rejected+deleted ones - if (realmsToDelete.size === 0) - continue; - if (table.schema.indexes.some((idx) => idx.keyPath === 'realmId' || - (Array.isArray(idx.keyPath) && idx.keyPath[0] === 'realmId'))) { - // There's an index to use: - //console.debug(`REMOVAL: deleting all ${table.name} where realmId anyOf `, JSON.stringify([...realmsToDelete])); - yield table - .where('realmId') - .anyOf([...realmsToDelete]) - .delete(); - } - else { - // No index to use: - //console.debug(`REMOVAL: deleting all ${table.name} where realmId is any of `, JSON.stringify([...realmsToDelete]), realmsToDelete.size); - yield table - .filter((obj) => !!(obj === null || obj === void 0 ? void 0 : obj.realmId) && realmsToDelete.has(obj.realmId)) - .delete(); - } - } - } - }); -} -function filterServerChangesThroughAddedClientChanges(serverChanges, addedClientChanges) { - const changes = {}; - applyOperations(changes, serverChanges); - const localPostChanges = {}; - applyOperations(localPostChanges, addedClientChanges); - subtractChanges(changes, localPostChanges); - return toDBOperationSet(changes); -} - -function MessagesFromServerConsumer(db) { - const queue = []; - const readyToServe = new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(true); - const event = new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(null); - let isWorking = false; - let loopWarning = 0; - let loopDetection = [0, 0, 0, 0, 0, 0, 0, 0, 0, Date.now()]; - event.subscribe(() => __awaiter(this, void 0, void 0, function* () { - if (isWorking) - return; - if (queue.length > 0) { - isWorking = true; - loopDetection.shift(); - loopDetection.push(Date.now()); - readyToServe.next(false); - try { - yield consumeQueue(); - } - finally { - if (loopDetection[loopDetection.length - 1] - loopDetection[0] < - 10000) { - // Ten loops within 10 seconds. Slow down! - if (Date.now() - loopWarning < 5000) { - // Last time we did this, we ended up here too. Wait for a minute. - console.warn(`Slowing down websocket loop for one minute`); - loopWarning = Date.now() + 60000; - yield new Promise((resolve) => setTimeout(resolve, 60000)); - } - else { - // This is a one-time event. Just pause 10 seconds. - console.warn(`Slowing down websocket loop for 10 seconds`); - loopWarning = Date.now() + 10000; - yield new Promise((resolve) => setTimeout(resolve, 10000)); - } - } - isWorking = false; - readyToServe.next(true); - } - } - })); - function enqueue(msg) { - queue.push(msg); - event.next(null); - } - function consumeQueue() { - var _a, _b, _c, _d, _e, _f; - return __awaiter(this, void 0, void 0, function* () { - while (queue.length > 0) { - const msg = queue.shift(); - try { - // If the sync worker or service worker is syncing, wait 'til thei're done. - // It's no need to have two channels at the same time - even though it wouldnt - // be a problem - this is an optimization. - yield db.cloud.syncState - .pipe(filter(({ phase }) => phase === 'in-sync' || phase === 'error'), take(1)) - .toPromise(); - console.debug('processing msg', msg); - const persistedSyncState = db.cloud.persistedSyncState.value; - //syncState. - if (!msg) - continue; - switch (msg.type) { - case 'token-expired': - console.debug('WebSocket observable: Token expired. Refreshing token...'); - const user = db.cloud.currentUser.value; - // Refresh access token - const refreshedLogin = yield refreshAccessToken(db.cloud.options.databaseUrl, user); - // Persist updated access token - yield db.table('$logins').update(user.userId, { - accessToken: refreshedLogin.accessToken, - accessTokenExpiration: refreshedLogin.accessTokenExpiration, - claims: refreshedLogin.claims, - license: refreshedLogin.license, - }); - // Updating $logins will trigger emission of db.cloud.currentUser observable, which - // in turn will lead to that connectWebSocket.ts will reconnect the socket with the - // new token. So we don't need to do anything more here. - break; - case 'realm-added': - if (!((_a = persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.realms) === null || _a === void 0 ? void 0 : _a.includes(msg.realm)) && - !((_b = persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.inviteRealms) === null || _b === void 0 ? void 0 : _b.includes(msg.realm))) { - yield db.cloud.sync({ purpose: 'pull', wait: true }); - //triggerSync(db, 'pull'); - } - break; - case 'realm-accepted': - if (!((_c = persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.realms) === null || _c === void 0 ? void 0 : _c.includes(msg.realm))) { - yield db.cloud.sync({ purpose: 'pull', wait: true }); - //triggerSync(db, 'pull'); - } - break; - case 'realm-removed': - if (((_d = persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.realms) === null || _d === void 0 ? void 0 : _d.includes(msg.realm)) || - ((_e = persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.inviteRealms) === null || _e === void 0 ? void 0 : _e.includes(msg.realm))) { - yield db.cloud.sync({ purpose: 'pull', wait: true }); - //triggerSync(db, 'pull'); - } - break; - case 'realms-changed': - //triggerSync(db, 'pull'); - yield db.cloud.sync({ purpose: 'pull', wait: true }); - break; - case 'changes': - console.debug('changes'); - if (((_f = db.cloud.syncState.value) === null || _f === void 0 ? void 0 : _f.phase) === 'error') { - triggerSync(db, 'pull'); - break; - } - yield db.transaction('rw', db.dx.tables, (tx) => __awaiter(this, void 0, void 0, function* () { - // @ts-ignore - tx.idbtrans.disableChangeTracking = true; - // @ts-ignore - tx.idbtrans.disableAccessControl = true; - const [schema, syncState, currentUser] = yield Promise.all([ - db.getSchema(), - db.getPersistedSyncState(), - db.getCurrentUser(), - ]); - console.debug('ws message queue: in transaction'); - if (!syncState || !schema || !currentUser) { - console.debug('required vars not present', { - syncState, - schema, - currentUser, - }); - return; // Initial sync must have taken place - otherwise, ignore this. - } - // Verify again in ACID tx that we're on same server revision. - if (msg.baseRev !== syncState.serverRevision) { - console.debug(`baseRev (${msg.baseRev}) differs from our serverRevision in syncState (${syncState.serverRevision})`); - // Should we trigger a sync now? No. This is a normal case - // when another local peer (such as the SW or a websocket channel on other tab) has - // updated syncState from new server information but we are not aware yet. It would - // be unnescessary to do a sync in that case. Instead, the caller of this consumeQueue() - // function will do readyToServe.next(true) right after this return, which will lead - // to a "ready" message being sent to server with the new accurate serverRev we have, - // so that the next message indeed will be correct. - if (typeof msg.baseRev === 'string' && // v2 format - (typeof syncState.serverRevision === 'bigint' || // v1 format - typeof syncState.serverRevision === 'object') // v1 format old browser - ) { - // The reason for the diff seems to be that server has migrated the revision format. - // Do a full sync to update revision format. - // If we don't do a sync request now, we could stuck in an endless loop. - triggerSync(db, 'pull'); - } - return; // Ignore message - } - // Verify also that the message is based on the exact same set of realms - const ourRealmSetHash = yield dexie__WEBPACK_IMPORTED_MODULE_0__["default"].waitFor( - // Keep TX in non-IDB work - computeRealmSetHash(syncState)); - console.debug('ourRealmSetHash', ourRealmSetHash); - if (ourRealmSetHash !== msg.realmSetHash) { - console.debug('not same realmSetHash', msg.realmSetHash); - triggerSync(db, 'pull'); - // The message isn't based on the same realms. - // Trigger a sync instead to resolve all things up. - return; - } - // Get clientChanges - let clientChanges = []; - if (currentUser.isLoggedIn) { - const mutationTables = getSyncableTables(db).map((tbl) => db.table(getMutationTable(tbl.name))); - clientChanges = yield listClientChanges(mutationTables, db); - console.debug('msg queue: client changes', clientChanges); - } - if (msg.changes.length > 0) { - const filteredChanges = filterServerChangesThroughAddedClientChanges(msg.changes, clientChanges); - // - // apply server changes - // - console.debug('applying filtered server changes', filteredChanges); - yield applyServerChanges(filteredChanges, db); - } - // Update latest revisions per table in case there are unsynced changes - // This can be a real case in future when we allow non-eagery sync. - // And it can actually be realistic now also, but very rare. - syncState.latestRevisions = getLatestRevisionsPerTable(clientChanges, syncState.latestRevisions); - syncState.serverRevision = msg.newRev; - // Update base revs - console.debug('Updating baseRefs', syncState.latestRevisions); - yield updateBaseRevs(db, schema, syncState.latestRevisions, msg.newRev); - // - // Update syncState - // - console.debug('Updating syncState', syncState); - yield db.$syncState.put(syncState, 'syncState'); - })); - console.debug('msg queue: done with rw transaction'); - break; - } - } - catch (error) { - console.error(`Error in msg queue`, error); - } - } - }); - } - return { - enqueue, - readyToServe, - }; -} - -const wm = new WeakMap(); -const DEXIE_CLOUD_SCHEMA = { - members: '@id, [userId+realmId], [email+realmId], realmId', - roles: '[realmId+name]', - realms: '@realmId', - $jobs: '', - $syncState: '', - $baseRevs: '[tableName+clientRev]', - $logins: 'claims.sub, lastLogin', -}; -let static_counter = 0; -function DexieCloudDB(dx) { - if ('vip' in dx) - dx = dx['vip']; // Avoid race condition. Always map to a vipped dexie that don't block during db.on.ready(). - let db = wm.get(dx.cloud); - if (!db) { - const localSyncEvent = new rxjs__WEBPACK_IMPORTED_MODULE_6__.Subject(); - let syncStateChangedEvent = new BroadcastedAndLocalEvent(`syncstatechanged-${dx.name}`); - let syncCompleteEvent = new BroadcastedAndLocalEvent(`synccomplete-${dx.name}`); - localSyncEvent['id'] = ++static_counter; - let initiallySynced = false; - db = { - get name() { - return dx.name; - }, - close() { - return dx.close(); - }, - transaction: dx.transaction.bind(dx), - table: dx.table.bind(dx), - get tables() { - return dx.tables; - }, - cloud: dx.cloud, - get $jobs() { - return dx.table('$jobs'); - }, - get $syncState() { - return dx.table('$syncState'); - }, - get $baseRevs() { - return dx.table('$baseRevs'); - }, - get $logins() { - return dx.table('$logins'); - }, - get realms() { - return dx.realms; - }, - get members() { - return dx.members; - }, - get roles() { - return dx.roles; - }, - get initiallySynced() { - return initiallySynced; - }, - localSyncEvent, - get syncStateChangedEvent() { - return syncStateChangedEvent; - }, - get syncCompleteEvent() { - return syncCompleteEvent; - }, - dx, - }; - const helperMethods = { - getCurrentUser() { - return db.$logins - .toArray() - .then((logins) => logins.find((l) => l.isLoggedIn) || UNAUTHORIZED_USER); - }, - getPersistedSyncState() { - return db.$syncState.get('syncState'); - }, - getSchema() { - return db.$syncState.get('schema').then((schema) => { - if (schema) { - for (const table of db.tables) { - if (table.schema.primKey && table.schema.primKey.keyPath && schema[table.name]) { - schema[table.name].primaryKey = nameFromKeyPath(table.schema.primKey.keyPath); - } - } - } - return schema; - }); - }, - getOptions() { - return db.$syncState.get('options'); - }, - setInitiallySynced(value) { - initiallySynced = value; - }, - reconfigure() { - syncStateChangedEvent = new BroadcastedAndLocalEvent(`syncstatechanged-${dx.name}`); - syncCompleteEvent = new BroadcastedAndLocalEvent(`synccomplete-${dx.name}`); - }, - }; - Object.assign(db, helperMethods); - db.messageConsumer = MessagesFromServerConsumer(db); - wm.set(dx.cloud, db); - } - return db; -} -function nameFromKeyPath(keyPath) { - return typeof keyPath === 'string' ? - keyPath : - keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; -} - -// @ts-ignore -const isFirefox = typeof InstallTrigger !== 'undefined'; - -const isSafari = typeof navigator !== 'undefined' && - /Safari\//.test(navigator.userAgent) && - !/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent); -const safariVersion = isSafari - ? // @ts-ignore - [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] - : NaN; - -// What we know: Safari 14.1 (version 605) crashes when using dexie-cloud's service worker. -// We don't know what exact call is causing this. Have tried safari-14-idb-fix with no luck. -// Something we do in the service worker is triggering the crash. -// When next Safari version (606) is out we will start enabling SW again, hoping that the bug is solved. -// If not, we might increment 605 to 606. -const DISABLE_SERVICEWORKER_STRATEGY = (isSafari && safariVersion <= 605) || // Disable for Safari for now. - isFirefox; // Disable for Firefox for now. Seems to have a bug in reading CryptoKeys from IDB from service workers - -/* Helper function to subscribe to database close no matter if it was unexpectedly closed or manually using db.close() - */ -function dbOnClosed(db, handler) { - db.on.close.subscribe(handler); - // @ts-ignore - const origClose = db._close; - // @ts-ignore - db._close = function () { - origClose.call(this); - handler(); - }; - return () => { - db.on.close.unsubscribe(handler); - // @ts-ignore - db._close = origClose; - }; -} - -const IS_SERVICE_WORKER = typeof self !== "undefined" && "clients" in self && !self.document; - -function throwVersionIncrementNeeded() { - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].SchemaError(`Version increment needed to allow dexie-cloud change tracking`); -} - -const { toString } = {}; -function toStringTag(o) { - return toString.call(o).slice(8, -1); -} -function getEffectiveKeys(primaryKey, req) { - var _a; - if (req.type === 'delete') - return req.keys; - return ((_a = req.keys) === null || _a === void 0 ? void 0 : _a.slice()) || req.values.map(primaryKey.extractKey); -} -function applyToUpperBitFix(orig, bits) { - return ((bits & 1 ? orig[0].toUpperCase() : orig[0].toLowerCase()) + - (bits & 2 ? orig[1].toUpperCase() : orig[1].toLowerCase()) + - (bits & 4 ? orig[2].toUpperCase() : orig[2].toLowerCase())); -} -const consonants = /b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i; -function isUpperCase(ch) { - return ch >= 'A' && ch <= 'Z'; -} -function generateTablePrefix(tableName, allPrefixes) { - let rv = tableName[0].toLocaleLowerCase(); // "users" = "usr", "friends" = "frn", "realms" = "rlm", etc. - for (let i = 1, l = tableName.length; i < l && rv.length < 3; ++i) { - if (consonants.test(tableName[i]) || isUpperCase(tableName[i])) - rv += tableName[i].toLowerCase(); - } - while (allPrefixes.has(rv)) { - if (/\d/g.test(rv)) { - rv = rv.substr(0, rv.length - 1) + (rv[rv.length - 1] + 1); - if (rv.length > 3) - rv = rv.substr(0, 3); - else - continue; - } - else if (rv.length < 3) { - rv = rv + '2'; - continue; - } - let bitFix = 1; - let upperFixed = rv; - while (allPrefixes.has(upperFixed) && bitFix < 8) { - upperFixed = applyToUpperBitFix(rv, bitFix); - ++bitFix; - } - if (bitFix < 8) - rv = upperFixed; - else { - let nextChar = (rv.charCodeAt(2) + 1) & 127; - rv = rv.substr(0, 2) + String.fromCharCode(nextChar); - // Here, in theory we could get an infinite loop if having 127*8 table names with identical 3 first consonants. - } - } - return rv; -} -let time = 0; -/** - * - * @param prefix A unique 3-letter short-name of the table. - * @param shardKey 3 last letters from another ID if colocation is requested. Verified on server on inserts - guarantees unique IDs across shards. - * The shardKey part of the key represent the shardId where it was first created. An object with this - * primary key can later on be moved to another shard without being altered. The reason for having - * the origin shardKey as part of the key, is that the server will not need to check uniqueness constraint - * across all shards on every insert. Updates / moves across shards are already controlled by the server - * in the sense that the objects needs to be there already - we only need this part for inserts. - * @returns - */ -function generateKey(prefix, shardKey) { - const a = new Uint8Array(18); - const timePart = new Uint8Array(a.buffer, 0, 6); - const now = Date.now(); // Will fit into 6 bytes until year 10 895. - if (time >= now) { - // User is bulk-creating objects the same millisecond. - // Increment the time part by one millisecond for each item. - // If bulk-creating 1,000,000 rows client-side in 10 seconds, - // the last time-stamp will be 990 seconds in future, which is no biggie at all. - // The point is to create a nice order of the generated IDs instead of - // using random ids. - ++time; - } - else { - time = now; - } - timePart[0] = time / 1099511627776; // Normal division (no bitwise operator) --> works with >= 32 bits. - timePart[1] = time / 4294967296; - timePart[2] = time / 16777216; - timePart[3] = time / 65536; - timePart[4] = time / 256; - timePart[5] = time; - const randomPart = new Uint8Array(a.buffer, 6); - crypto.getRandomValues(randomPart); - const id = new Uint8Array(a.buffer); - return prefix + b64LexEncode(id) + (shardKey || ''); -} - -function createIdGenerationMiddleware(db) { - return { - stack: 'dbcore', - name: 'idGenerationMiddleware', - level: 1, - create: (core) => { - return Object.assign(Object.assign({}, core), { table: (tableName) => { - const table = core.table(tableName); - function generateOrVerifyAtKeys(req, idPrefix) { - let valueClones = null; - const keys = getEffectiveKeys(table.schema.primaryKey, req); - keys.forEach((key, idx) => { - if (key === undefined) { - // Generate the key - const colocatedId = req.values[idx].realmId || db.cloud.currentUserId; - const shardKey = colocatedId.substr(colocatedId.length - 3); - keys[idx] = generateKey(idPrefix, shardKey); - if (!table.schema.primaryKey.outbound) { - if (!valueClones) - valueClones = req.values.slice(); - valueClones[idx] = dexie__WEBPACK_IMPORTED_MODULE_0__["default"].deepClone(valueClones[idx]); - dexie__WEBPACK_IMPORTED_MODULE_0__["default"].setByKeyPath(valueClones[idx], table.schema.primaryKey.keyPath, keys[idx]); - } - } - else if (typeof key !== 'string' || - (!key.startsWith(idPrefix) && !key.startsWith('#' + idPrefix))) { - // Key was specified by caller. Verify it complies with id prefix. - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].ConstraintError(`The ID "${key}" is not valid for table "${tableName}". ` + - `Primary '@' keys requires the key to be prefixed with "${idPrefix}" (or "#${idPrefix}).\n` + - `If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`); - } - }); - return table.mutate(Object.assign(Object.assign({}, req), { keys, values: valueClones || req.values })); - } - return Object.assign(Object.assign({}, table), { mutate: (req) => { - var _a, _b; - // @ts-ignore - if (req.trans.disableChangeTracking) { - // Disable ID policy checks and ID generation - return table.mutate(req); - } - if (req.type === 'add' || req.type === 'put') { - const cloudTableSchema = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[tableName]; - if (!(cloudTableSchema === null || cloudTableSchema === void 0 ? void 0 : cloudTableSchema.generatedGlobalId)) { - if (cloudTableSchema === null || cloudTableSchema === void 0 ? void 0 : cloudTableSchema.markedForSync) { - // Just make sure primary key is of a supported type: - const keys = getEffectiveKeys(table.schema.primaryKey, req); - keys.forEach((key, idx) => { - if (!isValidSyncableID(key)) { - const type = Array.isArray(key) - ? key.map(toStringTag).join(',') - : toStringTag(key); - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].ConstraintError(`Invalid primary key type ${type} for table ${tableName}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`); - } - }); - } - } - else { - if (((_b = db.cloud.options) === null || _b === void 0 ? void 0 : _b.databaseUrl) && !db.initiallySynced) { - // A database URL is configured but no initial sync has been performed. - const keys = getEffectiveKeys(table.schema.primaryKey, req); - // Check if the operation would yield any INSERT. If so, complain! We never want wrong ID prefixes stored. - return table - .getMany({ keys, trans: req.trans, cache: 'immutable' }) - .then((results) => { - if (results.length < keys.length) { - // At least one of the given objects would be created. Complain since - // the generated ID would be based on a locally computed ID prefix only - we wouldn't - // know if the server would give the same ID prefix until an initial sync has been - // performed. - throw new Error(`Unable to create new objects without an initial sync having been performed.`); - } - return table.mutate(req); - }); - } - return generateOrVerifyAtKeys(req, cloudTableSchema.idPrefix); - } - } - return table.mutate(req); - } }); - } }); - }, - }; -} - -function createImplicitPropSetterMiddleware(db) { - return { - stack: 'dbcore', - name: 'implicitPropSetterMiddleware', - level: 1, - create: (core) => { - return Object.assign(Object.assign({}, core), { table: (tableName) => { - const table = core.table(tableName); - return Object.assign(Object.assign({}, table), { mutate: (req) => { - var _a, _b, _c, _d; - // @ts-ignore - if (req.trans.disableChangeTracking) { - return table.mutate(req); - } - const trans = req.trans; - if ((_b = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[tableName]) === null || _b === void 0 ? void 0 : _b.markedForSync) { - if (req.type === 'add' || req.type === 'put') { - if (tableName === 'members') { - for (const member of req.values) { - if (typeof member.email === 'string') { - // Resolve https://github.com/dexie/dexie-cloud/issues/4 - // If adding a member, make sure email is lowercase and trimmed. - // This is to avoid issues where the APP does not check this - // and just allows the user to enter an email address that might - // have been pasted by the user from a source that had a trailing - // space or was in uppercase. We want to avoid that the user - // creates a new member with a different email address than - // the one he/she intended to create. - member.email = member.email.trim().toLowerCase(); - } - } - } - // No matter if user is logged in or not, make sure "owner" and "realmId" props are set properly. - // If not logged in, this will be changed upon syncification of the tables (next sync after login), - // however, application code will work better if we can always rely on that the properties realmId - // and owner are set. Application code may index them and query them based on db.cloud.currentUserId, - // and expect them to be returned. That scenario must work also when db.cloud.currentUserId === 'unauthorized'. - for (const obj of req.values) { - if (!obj.owner) { - obj.owner = trans.currentUser.userId; - } - if (!obj.realmId) { - obj.realmId = trans.currentUser.userId; - } - const key = (_d = (_c = table.schema.primaryKey).extractKey) === null || _d === void 0 ? void 0 : _d.call(_c, obj); - if (typeof key === 'string' && key[0] === '#') { - // Add $ts prop for put operations and - // disable update operations as well as consistent - // modify operations. Reason: Server may not have - // the object. Object should be created on server only - // if is being updated. An update operation won't create it - // so we must delete req.changeSpec to degrade operation to - // an upsert operation with timestamp so that it will be created. - // We must also degrade from consistent modify operations for the - // same reason - object might be there on server. Must but put up instead. - // FUTURE: This clumpsy behavior of private IDs could be refined later. - // Suggestion is to in future, treat private IDs as we treat all objects - // and sync operations normally. Only that deletions should become soft deletes - // for them - so that server knows when a private ID has been deleted on server - // not accept insert/upserts on them. - if (req.type === 'put') { - delete req.criteria; - delete req.changeSpec; - delete req.updates; - obj.$ts = Date.now(); - } - } - } - } - } - return table.mutate(req); - } }); - } }); - }, - }; -} - -function allSettled(possiblePromises) { - return new Promise(resolve => { - if (possiblePromises.length === 0) - resolve([]); - let remaining = possiblePromises.length; - const results = new Array(remaining); - possiblePromises.forEach((p, i) => Promise.resolve(p).then(value => results[i] = { status: "fulfilled", value }, reason => results[i] = { status: "rejected", reason }) - .then(() => --remaining || resolve(results))); - }); -} - -let counter$1 = 0; -function guardedTable(table) { - const prop = "$lock" + (++counter$1); - return Object.assign(Object.assign({}, table), { count: readLock(table.count, prop), get: readLock(table.get, prop), getMany: readLock(table.getMany, prop), openCursor: readLock(table.openCursor, prop), query: readLock(table.query, prop), mutate: writeLock(table.mutate, prop) }); -} -function readLock(fn, prop) { - return function readLocker(req) { - const { readers, writers, } = req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] }); - const numWriters = writers.length; - const promise = (numWriters > 0 - ? writers[numWriters - 1].then(() => fn(req), () => fn(req)) - : fn(req)).finally(() => { readers.splice(readers.indexOf(promise)); }); - readers.push(promise); - return promise; - }; -} -function writeLock(fn, prop) { - return function writeLocker(req) { - const { readers, writers, } = req.trans[prop] || (req.trans[prop] = { writers: [], readers: [] }); - let promise = (writers.length > 0 - ? writers[writers.length - 1].then(() => fn(req), () => fn(req)) - : readers.length > 0 - ? allSettled(readers).then(() => fn(req)) - : fn(req)).finally(() => { writers.shift(); }); - writers.push(promise); - return promise; - }; -} - -const outstandingTransactions = new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(new Set()); - -function isEagerSyncDisabled(db) { - var _a, _b, _c, _d; - return (((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.disableEagerSync) || - ((_c = (_b = db.cloud.currentUser.value) === null || _b === void 0 ? void 0 : _b.license) === null || _c === void 0 ? void 0 : _c.status) !== 'ok' || - !((_d = db.cloud.options) === null || _d === void 0 ? void 0 : _d.databaseUrl)); -} - -/** Tracks all mutations in the same transaction as the mutations - - * so it is guaranteed that no mutation goes untracked - and if transaction - * aborts, the mutations won't be tracked. - * - * The sync job will use the tracked mutations as the source of truth when pushing - * changes to server and cleanup the tracked mutations once the server has - * ackowledged that it got them. - */ -function createMutationTrackingMiddleware({ currentUserObservable, db, }) { - return { - stack: 'dbcore', - name: 'MutationTrackingMiddleware', - level: 1, - create: (core) => { - const ordinaryTables = core.schema.tables.filter((t) => !/^\$/.test(t.name)); - let mutTableMap; - try { - mutTableMap = new Map(ordinaryTables.map((tbl) => [ - tbl.name, - core.table(`$${tbl.name}_mutations`), - ])); - } - catch (_a) { - throwVersionIncrementNeeded(); - } - return Object.assign(Object.assign({}, core), { transaction: (tables, mode) => { - let tx; - if (mode === 'readwrite') { - const mutationTables = tables - .filter((tbl) => { var _a, _b; return (_b = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[tbl]) === null || _b === void 0 ? void 0 : _b.markedForSync; }) - .map((tbl) => getMutationTable(tbl)); - tx = core.transaction([...tables, ...mutationTables], mode); - } - else { - tx = core.transaction(tables, mode); - } - if (mode === 'readwrite') { - // Give each transaction a globally unique id. - tx.txid = randomString(16); - tx.opCount = 0; - // Introduce the concept of current user that lasts through the entire transaction. - // This is important because the tracked mutations must be connected to the user. - tx.currentUser = currentUserObservable.value; - outstandingTransactions.value.add(tx); - outstandingTransactions.next(outstandingTransactions.value); - const removeTransaction = () => { - tx.removeEventListener('complete', txComplete); - tx.removeEventListener('error', removeTransaction); - tx.removeEventListener('abort', removeTransaction); - outstandingTransactions.value.delete(tx); - outstandingTransactions.next(outstandingTransactions.value); - }; - const txComplete = () => { - if (tx.mutationsAdded && - !isEagerSyncDisabled(db)) { - triggerSync(db, 'push'); - } - removeTransaction(); - }; - tx.addEventListener('complete', txComplete); - tx.addEventListener('error', removeTransaction); - tx.addEventListener('abort', removeTransaction); - } - return tx; - }, table: (tableName) => { - const table = core.table(tableName); - if (/^\$/.test(tableName)) { - if (tableName.endsWith('_mutations')) { - // In case application code adds items to ..._mutations tables, - // make sure to set the mutationsAdded flag on transaction. - // This is also done in mutateAndLog() as that function talks to a - // lower level DBCore and wouldn't be catched by this code. - return Object.assign(Object.assign({}, table), { mutate: (req) => { - if (req.type === 'add' || req.type === 'put') { - req.trans.mutationsAdded = true; - } - return table.mutate(req); - } }); - } - else if (tableName === '$logins') { - return Object.assign(Object.assign({}, table), { mutate: (req) => { - //console.debug('Mutating $logins table', req); - return table - .mutate(req) - .then((res) => { - //console.debug('Mutating $logins'); - req.trans.mutationsAdded = true; - //console.debug('$logins mutated'); - return res; - }) - .catch((err) => { - console.debug('Failed mutation $logins', err); - return Promise.reject(err); - }); - } }); - } - else { - return table; - } - } - const { schema } = table; - const mutsTable = mutTableMap.get(tableName); - return guardedTable(Object.assign(Object.assign({}, table), { mutate: (req) => { - var _a, _b, _c; - const trans = req.trans; - if (!trans.txid) - return table.mutate(req); // Upgrade transactions not guarded by us. - if (trans.disableChangeTracking) - return table.mutate(req); - if (!((_b = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[tableName]) === null || _b === void 0 ? void 0 : _b.markedForSync)) - return table.mutate(req); - if (!((_c = trans.currentUser) === null || _c === void 0 ? void 0 : _c.isLoggedIn)) { - // Unauthorized user should not log mutations. - // Instead, after login all local data should be logged at once. - return table.mutate(req); - } - return req.type === 'deleteRange' - ? table - // Query the actual keys (needed for server sending correct rollback to us) - .query({ - query: { range: req.range, index: schema.primaryKey }, - trans: req.trans, - values: false, - }) - // Do a delete request instead, but keep the criteria info for the server to execute - .then((res) => { - return mutateAndLog({ - type: 'delete', - keys: res.result, - trans: req.trans, - criteria: { index: null, range: req.range }, - }); - }) - : mutateAndLog(req); - } })); - function mutateAndLog(req) { - const trans = req.trans; - trans.mutationsAdded = true; - const { txid, currentUser: { userId }, } = trans; - const { type } = req; - const opNo = ++trans.opCount; - return table.mutate(req).then((res) => { - const { numFailures: hasFailures, failures } = res; - let keys = type === 'delete' ? req.keys : res.results; - let values = 'values' in req ? req.values : []; - let updates = 'updates' in req && req.updates; - if (hasFailures) { - keys = keys.filter((_, idx) => !failures[idx]); - values = values.filter((_, idx) => !failures[idx]); - } - const ts = Date.now(); - const mut = req.type === 'delete' - ? { - type: 'delete', - ts, - opNo, - keys, - criteria: req.criteria, - txid, - userId, - } - : req.type === 'add' - ? { - type: 'insert', - ts, - opNo, - keys, - txid, - userId, - values, - } - : req.criteria && req.changeSpec - ? { - // Common changeSpec for all keys - type: 'modify', - ts, - opNo, - keys, - criteria: req.criteria, - changeSpec: req.changeSpec, - txid, - userId, - } - : updates - ? { - // One changeSpec per key - type: 'update', - ts, - opNo, - keys: updates.keys, - changeSpecs: updates.changeSpecs, - txid, - userId, - } - : { - type: 'upsert', - ts, - opNo, - keys, - values, - txid, - userId, - }; - return keys.length > 0 || ('criteria' in req && req.criteria) - ? mutsTable - .mutate({ type: 'add', trans, values: [mut] }) // Log entry - .then(() => res) // Return original response - : res; - }); - } - } }); - }, - }; -} - -function overrideParseStoresSpec(origFunc, dexie) { - return function (stores, dbSchema) { - const storesClone = Object.assign(Object.assign({}, DEXIE_CLOUD_SCHEMA), stores); - // Merge indexes of DEXIE_CLOUD_SCHEMA with stores - Object.keys(DEXIE_CLOUD_SCHEMA).forEach((tableName) => { - const schemaSrc = storesClone[tableName]; - // Verify that they don't try to delete a table that is needed for access control of Dexie Cloud - if (schemaSrc == null) { - // They try to delete one of the built-in schema tables. - throw new Error(`Cannot delete table ${tableName} as it is needed for access control of Dexie Cloud`); - } - // If not trying to override a built-in table, then we can skip this and continue to next table. - if (!stores[tableName]) { - // They haven't tried to declare this table. No need to merge indexes. - return; // Continue - } - // They have declared this table. Merge indexes in case they didn't declare all indexes we need. - const requestedIndexes = schemaSrc.split(',').map(spec => spec.trim()); - const builtInIndexes = DEXIE_CLOUD_SCHEMA[tableName].split(',').map(spec => spec.trim()); - const requestedIndexSet = new Set(requestedIndexes.map(index => index.replace(/([&*]|\+\+)/g, ""))); - // Verify that primary key is unchanged - if (requestedIndexes[0] !== builtInIndexes[0]) { - // Primary key must match exactly - throw new Error(`Cannot override primary key of table ${tableName}. Please declare it as {${tableName}: ${JSON.stringify(DEXIE_CLOUD_SCHEMA[tableName])}`); - } - // Merge indexes - for (let i = 1; i < builtInIndexes.length; ++i) { - const builtInIndex = builtInIndexes[i]; - if (!requestedIndexSet.has(builtInIndex.replace(/([&*]|\+\+)/g, ""))) { - // Add built-in index if not already requested - storesClone[tableName] += `,${builtInIndex}`; - } - } - }); - // Populate dexie.cloud.schema - const cloudSchema = dexie.cloud.schema || (dexie.cloud.schema = {}); - const allPrefixes = new Set(); - Object.keys(storesClone).forEach(tableName => { - const schemaSrc = storesClone[tableName]; - const cloudTableSchema = cloudSchema[tableName] || (cloudSchema[tableName] = {}); - if (schemaSrc != null) { - if (/^\@/.test(schemaSrc)) { - storesClone[tableName] = storesClone[tableName].substr(1); - cloudTableSchema.generatedGlobalId = true; - cloudTableSchema.idPrefix = generateTablePrefix(tableName, allPrefixes); - allPrefixes.add(cloudTableSchema.idPrefix); - } - if (!/^\$/.test(tableName)) { - storesClone[`$${tableName}_mutations`] = '++rev'; - cloudTableSchema.markedForSync = true; - } - if (cloudTableSchema.deleted) { - cloudTableSchema.deleted = false; - } - } - else { - cloudTableSchema.deleted = true; - cloudTableSchema.markedForSync = false; - storesClone[`$${tableName}_mutations`] = null; - } - }); - const rv = origFunc.call(this, storesClone, dbSchema); - return rv; - }; -} - -function performInitialSync(db, cloudOptions, cloudSchema) { - return __awaiter(this, void 0, void 0, function* () { - console.debug('Performing initial sync'); - yield sync(db, cloudOptions, cloudSchema, { isInitialSync: true }); - console.debug('Done initial sync'); - }); -} - -const USER_INACTIVITY_TIMEOUT = 180000; // 3 minutes -const INACTIVE_WAIT_TIME = 20000; -// This observable will be emitted to later down.... -const userIsActive = new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(true); -// A refined version that waits before changing state: -// * Wait another INACTIVE_WAIT_TIME before accepting that the user is inactive. -// Reason 1: Spare resources - no need to setup the entire websocket flow when -// switching tabs back and forth. -// Reason 2: Less flickering for the end user when switching tabs back and forth. -// * Wait another ACTIVE_WAIT_TIME before accepting that the user is active. -// Possible reason to have a value here: Sparing resources if users often temporary click the tab -// for just a short time. -const userIsReallyActive = new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(true); -userIsActive - .pipe(switchMap((isActive) => { - //console.debug('SyncStatus: DUBB: isActive changed to', isActive); - return isActive - ? (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(true) - : (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(false).pipe(delay(INACTIVE_WAIT_TIME)) - ; -}), distinctUntilChanged()) - .subscribe(userIsReallyActive); -// -// First create some corner-stone observables to build the flow on -// -// document.onvisibilitychange: -const visibilityStateIsChanged = typeof document !== 'undefined' - ? (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(document, 'visibilitychange') - : (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)({}); -// document.onvisibilitychange makes document hidden: -const documentBecomesHidden = visibilityStateIsChanged.pipe(filter(() => document.visibilityState === 'hidden')); -// document.onvisibilitychange makes document visible -const documentBecomesVisible = visibilityStateIsChanged.pipe(filter(() => document.visibilityState === 'visible')); -// Any of various user-activity-related events happen: -const userDoesSomething = typeof window !== 'undefined' - ? (0,rxjs__WEBPACK_IMPORTED_MODULE_9__.merge)(documentBecomesVisible, (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(window, 'mousedown'), (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(window, 'mousemove'), (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(window, 'keydown'), (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(window, 'wheel'), (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(window, 'touchmove')) - : (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)({}); -if (typeof document !== 'undefined') { - // - // Now, create a final observable and start subscribing to it in order - // to make it emit values to userIsActive BehaviourSubject (which is the - // most important global hot observable we have here) - // - // Live test: https://jsitor.com/LboCDHgbn - // - (0,rxjs__WEBPACK_IMPORTED_MODULE_9__.merge)((0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(true), // Make sure something is always emitted from start - documentBecomesHidden, // so that we can eagerly emit false! - userDoesSomething) - .pipe( - // No matter event source, compute whether user is visible using visibilityState: - map(() => document.visibilityState === 'visible'), - // Make sure to emit it - tap((isActive) => { - if (userIsActive.value !== isActive) { - // Emit new value unless it already has that value - userIsActive.next(isActive); - } - }), - // Now, if true was emitted, make sure to set a timeout to emit false - // unless new user activity things happen (in that case, the timeout will be cancelled!) - switchMap((isActive) => isActive - ? (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(0).pipe(delay(USER_INACTIVITY_TIMEOUT - INACTIVE_WAIT_TIME), tap(() => userIsActive.next(false))) - : (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(0))) - .subscribe(() => { }); // Unless we subscribe nothing will be propagated to userIsActive observable -} - -class TokenExpiredError extends Error { - constructor() { - super(...arguments); - this.name = "TokenExpiredError"; - } -} - -const SERVER_PING_TIMEOUT = 20000; -const CLIENT_PING_INTERVAL = 30000; -const FAIL_RETRY_WAIT_TIME = 60000; -class WSObservable extends rxjs__WEBPACK_IMPORTED_MODULE_4__.Observable { - constructor(databaseUrl, rev, realmSetHash, clientIdentity, messageProducer, webSocketStatus, token, tokenExpiration) { - super((subscriber) => new WSConnection(databaseUrl, rev, realmSetHash, clientIdentity, token, tokenExpiration, subscriber, messageProducer, webSocketStatus)); - } -} -let counter = 0; -class WSConnection extends rxjs__WEBPACK_IMPORTED_MODULE_10__.Subscription { - constructor(databaseUrl, rev, realmSetHash, clientIdentity, token, tokenExpiration, subscriber, messageProducer, webSocketStatus) { - super(() => this.teardown()); - this.id = ++counter; - this.reconnecting = false; - console.debug('New WebSocket Connection', this.id, token ? 'authorized' : 'unauthorized'); - this.databaseUrl = databaseUrl; - this.rev = rev; - this.realmSetHash = realmSetHash; - this.clientIdentity = clientIdentity; - this.token = token; - this.tokenExpiration = tokenExpiration; - this.subscriber = subscriber; - this.lastUserActivity = new Date(); - this.messageProducer = messageProducer; - this.messageProducerSubscription = null; - this.webSocketStatus = webSocketStatus; - this.connect(); - } - teardown() { - console.debug('Teardown WebSocket Connection', this.id); - this.disconnect(); - } - disconnect() { - this.webSocketStatus.next('disconnected'); - if (this.pinger) { - clearInterval(this.pinger); - this.pinger = null; - } - if (this.ws) { - try { - this.ws.close(); - } - catch (_a) { } - } - this.ws = null; - if (this.messageProducerSubscription) { - this.messageProducerSubscription.unsubscribe(); - this.messageProducerSubscription = null; - } - } - reconnect() { - if (this.reconnecting) - return; - this.reconnecting = true; - try { - this.disconnect(); - } - catch (_a) { } - this.connect() - .catch(() => { }) - .then(() => (this.reconnecting = false)); // finally() - } - connect() { - return __awaiter(this, void 0, void 0, function* () { - this.lastServerActivity = new Date(); - if (this.pauseUntil && this.pauseUntil > new Date()) { - console.debug('WS not reconnecting just yet', { - id: this.id, - pauseUntil: this.pauseUntil, - }); - return; - } - if (this.ws) { - throw new Error(`Called connect() when a connection is already open`); - } - if (!this.databaseUrl) - throw new Error(`Cannot connect without a database URL`); - if (this.closed) { - //console.debug('SyncStatus: DUBB: Ooops it was closed!'); - return; - } - if (this.tokenExpiration && this.tokenExpiration < new Date()) { - this.subscriber.error(new TokenExpiredError()); // Will be handled in connectWebSocket.ts. - return; - } - this.webSocketStatus.next('connecting'); - this.pinger = setInterval(() => __awaiter(this, void 0, void 0, function* () { - if (this.closed) { - console.debug('pinger check', this.id, 'CLOSED.'); - this.teardown(); - return; - } - if (this.ws) { - try { - this.ws.send(JSON.stringify({ type: 'ping' })); - setTimeout(() => { - console.debug('pinger setTimeout', this.id, this.pinger ? `alive` : 'dead'); - if (!this.pinger) - return; - if (this.closed) { - console.debug('pinger setTimeout', this.id, 'subscription is closed'); - this.teardown(); - return; - } - if (this.lastServerActivity < - new Date(Date.now() - SERVER_PING_TIMEOUT)) { - // Server inactive. Reconnect if user is active. - console.debug('pinger: server is inactive'); - console.debug('pinger reconnecting'); - this.reconnect(); - } - else { - console.debug('pinger: server still active'); - } - }, SERVER_PING_TIMEOUT); - } - catch (_a) { - console.debug('pinger catch error', this.id, 'reconnecting'); - this.reconnect(); - } - } - else { - console.debug('pinger', this.id, 'reconnecting'); - this.reconnect(); - } - }), CLIENT_PING_INTERVAL); - // The following vars are needed because we must know which callback to ack when server sends it's ack to us. - const wsUrl = new URL(this.databaseUrl); - wsUrl.protocol = wsUrl.protocol === 'http:' ? 'ws' : 'wss'; - const searchParams = new URLSearchParams(); - if (this.subscriber.closed) - return; - searchParams.set('v', '2'); - searchParams.set('rev', this.rev); - searchParams.set('realmsHash', this.realmSetHash); - searchParams.set('clientId', this.clientIdentity); - if (this.token) { - searchParams.set('token', this.token); - } - // Connect the WebSocket to given url: - console.debug('dexie-cloud WebSocket create'); - const ws = (this.ws = new WebSocket(`${wsUrl}/changes?${searchParams}`)); - //ws.binaryType = "arraybuffer"; // For future when subscribing to actual changes. - ws.onclose = (event) => { - if (!this.pinger) - return; - console.debug('dexie-cloud WebSocket onclosed', this.id); - this.reconnect(); - }; - ws.onmessage = (event) => { - if (!this.pinger) - return; - console.debug('dexie-cloud WebSocket onmessage', event.data); - this.lastServerActivity = new Date(); - try { - const msg = TSON.parse(event.data); - if (msg.type === 'error') { - throw new Error(`Error message from dexie-cloud: ${msg.error}`); - } - if (msg.type === 'rev') { - this.rev = msg.rev; // No meaning but seems reasonable. - } - if (msg.type !== 'pong') { - this.subscriber.next(msg); - } - } - catch (e) { - this.subscriber.error(e); - } - }; - try { - let everConnected = false; - yield new Promise((resolve, reject) => { - ws.onopen = (event) => { - console.debug('dexie-cloud WebSocket onopen'); - everConnected = true; - resolve(null); - }; - ws.onerror = (event) => { - if (!everConnected) { - const error = event.error || new Error('WebSocket Error'); - this.subscriber.error(error); - this.webSocketStatus.next('error'); - reject(error); - } - else { - this.reconnect(); - } - }; - }); - this.messageProducerSubscription = this.messageProducer.subscribe((msg) => { - var _a; - if (!this.closed) { - if (msg.type === 'ready' && - this.webSocketStatus.value !== 'connected') { - this.webSocketStatus.next('connected'); - } - (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(TSON.stringify(msg)); - } - }); - } - catch (error) { - this.pauseUntil = new Date(Date.now() + FAIL_RETRY_WAIT_TIME); - } - }); - } -} - -class InvalidLicenseError extends Error { - constructor(license) { - super(license === 'expired' - ? `License expired` - : license === 'deactivated' - ? `User deactivated` - : 'Invalid license'); - this.name = 'InvalidLicenseError'; - if (license) { - this.license = license; - } - } -} - -function sleep(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} -function waitAndReconnectWhenUserDoesSomething(error) { - return __awaiter(this, void 0, void 0, function* () { - console.error(`WebSocket observable: error but revive when user does some active thing...`, error); - // Sleep some seconds... - yield sleep(3000); - // Wait til user does something (move mouse, tap, scroll, click etc) - console.debug('waiting for someone to do something'); - yield userDoesSomething.pipe(take(1)).toPromise(); - console.debug('someone did something!'); - }); -} -function connectWebSocket(db) { - var _a; - if (!((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.databaseUrl)) { - throw new Error(`No database URL to connect WebSocket to`); - } - const messageProducer = db.messageConsumer.readyToServe.pipe(filter((isReady) => isReady), // When consumer is ready for new messages, produce such a message to inform server about it - switchMap(() => db.getPersistedSyncState()), // We need the info on which server revision we are at: - filter((syncState) => syncState && syncState.serverRevision), // We wont send anything to server before inital sync has taken place - switchMap((syncState) => __awaiter(this, void 0, void 0, function* () { - return ({ - // Produce the message to trigger server to send us new messages to consume: - type: 'ready', - rev: syncState.serverRevision, - realmSetHash: yield computeRealmSetHash(syncState) - }); - }))); - function createObservable() { - return db.cloud.persistedSyncState.pipe(filter((syncState) => syncState === null || syncState === void 0 ? void 0 : syncState.serverRevision), // Don't connect before there's no initial sync performed. - take(1), // Don't continue waking up whenever syncState change - switchMap((syncState) => db.cloud.currentUser.pipe(map((userLogin) => [userLogin, syncState]))), switchMap(([userLogin, syncState]) => { - /*if (userLogin.license?.status && userLogin.license.status !== 'ok') { - throw new InvalidLicenseError(); - }*/ - return userIsReallyActive.pipe(map((isActive) => [isActive ? userLogin : null, syncState])); - }), switchMap(([userLogin, syncState]) => { - if ((userLogin === null || userLogin === void 0 ? void 0 : userLogin.isLoggedIn) && !(syncState === null || syncState === void 0 ? void 0 : syncState.realms.includes(userLogin.userId))) { - // We're in an in-between state when user is logged in but the user's realms are not yet synced. - // Don't make this change reconnect the websocket just yet. Wait till syncState is updated - // to iclude the user's realm. - return db.cloud.persistedSyncState.pipe(filter((syncState) => (syncState === null || syncState === void 0 ? void 0 : syncState.realms.includes(userLogin.userId)) || false), take(1), map((syncState) => [userLogin, syncState])); - } - return new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject([userLogin, syncState]); - }), switchMap(([userLogin, syncState]) => __awaiter(this, void 0, void 0, function* () { return [userLogin, yield computeRealmSetHash(syncState)]; })), distinctUntilChanged(([prevUser, prevHash], [currUser, currHash]) => prevUser === currUser && prevHash === currHash), switchMap(([userLogin, realmSetHash]) => { - var _a; - if (!((_a = db.cloud.persistedSyncState) === null || _a === void 0 ? void 0 : _a.value)) { - // Restart the flow if persistedSyncState is not yet available. - return createObservable(); - } - // Let server end query changes from last entry of same client-ID and forward. - // If no new entries, server won't bother the client. If new entries, server sends only those - // and the baseRev of the last from same client-ID. - if (userLogin) { - return new WSObservable(db.cloud.options.databaseUrl, db.cloud.persistedSyncState.value.serverRevision, realmSetHash, db.cloud.persistedSyncState.value.clientIdentity, messageProducer, db.cloud.webSocketStatus, userLogin.accessToken, userLogin.accessTokenExpiration); - } - else { - return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)([]); - } - }), catchError((error) => { - if ((error === null || error === void 0 ? void 0 : error.name) === 'TokenExpiredError') { - console.debug('WebSocket observable: Token expired. Refreshing token...'); - return (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(true).pipe(switchMap(() => __awaiter(this, void 0, void 0, function* () { - // Refresh access token - const user = yield db.getCurrentUser(); - const refreshedLogin = yield refreshAccessToken(db.cloud.options.databaseUrl, user); - // Persist updated access token - yield db.table('$logins').update(user.userId, { - accessToken: refreshedLogin.accessToken, - accessTokenExpiration: refreshedLogin.accessTokenExpiration, - claims: refreshedLogin.claims, - license: refreshedLogin.license, - }); - })), switchMap(() => createObservable())); - } - else { - return (0,rxjs__WEBPACK_IMPORTED_MODULE_11__.throwError)(() => error); - } - }), catchError((error) => { - db.cloud.webSocketStatus.next("error"); - if (error instanceof InvalidLicenseError) { - // Don't retry. Just throw and don't try connect again. - return (0,rxjs__WEBPACK_IMPORTED_MODULE_11__.throwError)(() => error); - } - return (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(waitAndReconnectWhenUserDoesSomething(error)).pipe(switchMap(() => createObservable())); - })); - } - return createObservable().subscribe({ - next: (msg) => { - if (msg) { - console.debug('WS got message', msg); - db.messageConsumer.enqueue(msg); - } - }, - error: (error) => { - console.error('WS got error', error); - }, - complete: () => { - console.debug('WS observable completed'); - }, - }); -} - -function isSyncNeeded(db) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - return ((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.databaseUrl) && db.cloud.schema - ? yield sync(db, db.cloud.options, db.cloud.schema, { justCheckIfNeeded: true }) - : false; - }); -} - -function performGuardedJob(db, jobName, job) { - if (typeof navigator === 'undefined' || !navigator.locks) { - // No support for guarding jobs. IE11, node.js, etc. - return job(); - } - return navigator.locks.request(db.name + '|' + jobName, () => job()); -} - -const ongoingSyncs = new WeakMap(); -function syncIfPossible(db, cloudOptions, cloudSchema, options) { - const ongoing = ongoingSyncs.get(db); - if (ongoing) { - if (ongoing.pull || (options === null || options === void 0 ? void 0 : options.purpose) === 'push') { - console.debug('syncIfPossible(): returning the ongoing sync promise.'); - return ongoing.promise; - } - else { - // Ongoing sync may never do anything in case there are no outstanding changes - // to sync (because its purpose was "push" not "pull") - // Now, however, we are asked to do a sync with the purpose of "pull" - // We want to optimize here. We must wait for the ongoing to complete - // and then, if the ongoing sync never resulted in a sync request, - // we must redo the sync. - // To inspect what is happening in the ongoing request, let's subscribe - // to db.cloud.syncState and look for if it is doing any "pulling" phase: - let hasPullTakenPlace = false; - const subscription = db.cloud.syncState.subscribe((syncState) => { - if (syncState.phase === 'pulling') { - hasPullTakenPlace = true; - } - }); - // Ok, so now we are watching. At the same time, wait for the ongoing to complete - // and when it has completed, check if we're all set or if we need to redo - // the call: - return (ongoing.promise - // This is a finally block but we are still running tests on - // browsers that don't support it, so need to do it like this: - .then(() => { - subscription.unsubscribe(); - }) - .catch((error) => { - subscription.unsubscribe(); - return Promise.reject(error); - }) - .then(() => { - if (!hasPullTakenPlace) { - // No pull took place in the ongoing sync but the caller had "pull" as - // an explicit purpose of this call - so we need to redo the call! - return syncIfPossible(db, cloudOptions, cloudSchema, options); - } - })); - } - } - const promise = _syncIfPossible(); - ongoingSyncs.set(db, { promise, pull: (options === null || options === void 0 ? void 0 : options.purpose) !== 'push' }); - return promise; - function _syncIfPossible() { - return __awaiter(this, void 0, void 0, function* () { - try { - // Check if should delay sync due to ratelimit: - yield checkSyncRateLimitDelay(db); - // Check if we need to lock the sync job. Not needed if we are the service worker. - if (db.cloud.isServiceWorkerDB) { - // We are the dedicated sync SW: - yield sync(db, cloudOptions, cloudSchema, options); - } - else if (!db.cloud.usingServiceWorker) { - // We use a flow that is better suited for the case when multiple workers want to - // do the same thing. - yield performGuardedJob(db, CURRENT_SYNC_WORKER, () => sync(db, cloudOptions, cloudSchema, options)); - } - else { - assert(false); - throw new Error('Internal _syncIfPossible() - invalid precondition - should not have been called.'); - } - ongoingSyncs.delete(db); - console.debug('Done sync'); - } - catch (error) { - ongoingSyncs.delete(db); - console.error(`Failed to sync client changes`, error); - throw error; // Make sure we rethrow error so that sync event is retried. - // I don't think we should setTimout or so here. - // Unless server tells us to in some response. - // Then we could follow that advice but not by waiting here but by registering - // Something that triggers an event listened to in startPushWorker() - } - }); - } -} - -const SECONDS = 1000; -const MINUTES = 60 * SECONDS; - -function LocalSyncWorker(db, cloudOptions, cloudSchema) { - let localSyncEventSubscription = null; - //let syncHandler: ((event: Event) => void) | null = null; - //let periodicSyncHandler: ((event: Event) => void) | null = null; - let cancelToken = { cancelled: false }; - let retryHandle = null; - let retryPurpose = null; // "pull" is superset of "push" - function syncAndRetry(purpose, retryNum = 1) { - // Use setTimeout() to get onto a clean stack and - // break free from possible active transaction: - setTimeout(() => { - if (retryHandle) - clearTimeout(retryHandle); - const combPurpose = retryPurpose === 'pull' ? 'pull' : purpose; - retryHandle = null; - retryPurpose = null; - syncIfPossible(db, cloudOptions, cloudSchema, { - cancelToken, - retryImmediatelyOnFetchError: true, // workaround for "net::ERR_NETWORK_CHANGED" in chrome. - purpose: combPurpose, - }).catch((e) => { - console.error('error in syncIfPossible()', e); - if (cancelToken.cancelled) { - stop(); - } - else if (retryNum < 3) { - // Mimic service worker sync event: retry 3 times - // * first retry after 5 minutes - // * second retry 15 minutes later - const combinedPurpose = retryPurpose && retryPurpose === 'pull' ? 'pull' : purpose; - const handle = setTimeout(() => syncAndRetry(combinedPurpose, retryNum + 1), [0, 5, 15][retryNum] * MINUTES); - // Cancel the previous retryHandle if it exists to avoid scheduling loads of retries. - if (retryHandle) - clearTimeout(retryHandle); - retryHandle = handle; - retryPurpose = combinedPurpose; - } - }); - }, 0); - } - const start = () => { - // Sync eagerly whenever a change has happened (+ initially when there's no syncState yet) - // This initial subscribe will also trigger an sync also now. - console.debug('Starting LocalSyncWorker', db.localSyncEvent['id']); - localSyncEventSubscription = db.localSyncEvent.subscribe(({ purpose }) => { - try { - syncAndRetry(purpose || 'pull'); - } - catch (err) { - console.error('What-the....', err); - } - }); - //setTimeout(()=>db.localSyncEvent.next({}), 5000); - }; - const stop = () => { - console.debug('Stopping LocalSyncWorker'); - cancelToken.cancelled = true; - if (localSyncEventSubscription) - localSyncEventSubscription.unsubscribe(); - }; - return { - start, - stop, - }; -} - -function updateSchemaFromOptions(schema, options) { - if (schema && options) { - if (options.unsyncedTables) { - for (const tableName of options.unsyncedTables) { - if (schema[tableName]) { - schema[tableName].markedForSync = false; - } - } - } - } -} - -function verifySchema(db) { - var _a, _b; - for (const table of db.tables) { - if ((_b = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[table.name]) === null || _b === void 0 ? void 0 : _b.markedForSync) { - if (table.schema.primKey.auto) { - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].SchemaError(`Table ${table.name} is both autoIncremented and synced. ` + - `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(table.name)}]}) to blacklist it from sync`); - } - if (!table.schema.primKey.keyPath) { - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].SchemaError(`Table ${table.name} cannot be both synced and outbound. ` + - `Use db.cloud.configure({unsyncedTables: [${JSON.stringify(table.name)}]}) to blacklist it from sync`); - } - } - } -} - -var n,l$1,u$1,t$1,o$1,f$1={},e$1=[],c$1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function s$1(n,l){for(var u in l)n[u]=l[u];return n}function a$1(n){var l=n.parentNode;l&&l.removeChild(n);}function h(l,u,i){var t,o,r,f={};for(r in u)"key"==r?t=u[r]:"ref"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):i),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===f[r]&&(f[r]=l.defaultProps[r]);return v$1(l,f,t,o,null)}function v$1(n,i,t,o,r){var f={type:n,props:i,key:t,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==r?++u$1:r};return null==r&&null!=l$1.vnode&&l$1.vnode(f),f}function p$1(n){return n.children}function d$1(n,l){this.props=n,this.context=l;}function _$1(n,l){if(null==l)return n.__?_$1(n.__,n.__.__k.indexOf(n)+1):null;for(var u;l0?v$1(k.type,k.props,k.key,null,k.__v):k)){if(k.__=u,k.__b=u.__b+1,null===(d=x[h])||d&&k.key==d.key&&k.type===d.type)x[h]=void 0;else for(y=0;y=i.__.length&&i.__.push({__V:f}),i.__[t]}function p(n){return o=1,y(z,n)}function y(n,u,i){var o=d(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):z(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}));}],o.__c=r,!r.u)){r.u=!0;var c=r.shouldComponentUpdate;r.shouldComponentUpdate=function(n,t,r){if(!o.__c.__H)return !0;var u=o.__c.__H.__.filter(function(n){return n.__c});if(u.every(function(n){return !n.__N}))return !c||c.call(this,n,t,r);var i=!1;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0);}}),!!i&&(!c||c.call(this,n,t,r))};}return o.__N||o.__}function s(u,i){var o=d(t++,4);!l$1.__s&&w(o.__H,i)&&(o.__=u,o.i=i,r.__h.push(o));}function _(n){return o=5,F(function(){return {current:n}},[])}function F(n,r){var u=d(t++,7);return w(u.__H,r)?(u.__V=n(),u.i=r,u.__h=n,u.__V):u.__}function b(){for(var t;t=c.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(j),t.__H.__h.forEach(k),t.__H.__h=[];}catch(r){t.__H.__h=[],l$1.__e(r,t.__v);}}l$1.__b=function(n){r=null,e&&e(n);},l$1.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.__V=f,n.__N=n.i=void 0;})):(i.__h.forEach(j),i.__h.forEach(k),i.__h=[])),u=r;},l$1.diffed=function(t){v&&v(t);var o=t.__c;o&&o.__H&&(o.__H.__h.length&&(1!==c.push(o)&&i===l$1.requestAnimationFrame||((i=l$1.requestAnimationFrame)||function(n){var t,r=function(){clearTimeout(u),g&&cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(r,100);g&&(t=requestAnimationFrame(r));})(b)),o.__H.__.forEach(function(n){n.i&&(n.__H=n.i),n.__V!==f&&(n.__=n.__V),n.i=void 0,n.__V=f;})),u=r=null;},l$1.__c=function(t,r){r.some(function(t){try{t.__h.forEach(j),t.__h=t.__h.filter(function(n){return !n.__||k(n)});}catch(u){r.some(function(n){n.__h&&(n.__h=[]);}),r=[],l$1.__e(u,t.__v);}}),l&&l(t,r);},l$1.unmount=function(t){m&&m(t);var r,u=t.__c;u&&u.__H&&(u.__H.__.forEach(function(n){try{j(n);}catch(n){r=n;}}),r&&l$1.__e(r,u.__v));};var g="function"==typeof requestAnimationFrame;function j(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t;}function k(n){var t=r;n.__c=n.__(),r=t;}function w(n,t){return !n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function z(n,t){return "function"==typeof t?t(n):t} - -/** Resolve a message template with parameters. - * - * Example: - * resolveText({ - * message: "Hello {name}!", - * messageCode: "HELLO", - * messageParams: {name: "David"} - * }) => "Hello David!" - * - * @param message Template message with {vars} in it. - * @param messageCode Unique code for the message. Can be used for translation. - * @param messageParams Parameters to be used in the message. - * @returns A final message where parameters have been replaced with values. - */ -function resolveText({ message, messageCode, messageParams }) { - return message.replace(/\{\w+\}/ig, n => messageParams[n.substring(1, n.length - 1)]); -} - -const OTP_LENGTH = 8; -function LoginDialog({ title, type, alerts, fields, submitLabel, cancelLabel, onCancel, onSubmit, }) { - const [params, setParams] = p({}); - const firstFieldRef = _(null); - s(() => { var _a; return (_a = firstFieldRef.current) === null || _a === void 0 ? void 0 : _a.focus(); }, []); - return (h(Dialog, { className: "dxc-login-dlg" }, - h(p$1, null, - h("h3", { style: Styles.WindowHeader }, title), - alerts.map((alert) => (h("p", { style: Styles.Alert[alert.type] }, resolveText(alert)))), - h("form", { onSubmit: (ev) => { - ev.preventDefault(); - onSubmit(params); - } }, Object.entries(fields).map(([fieldName, { type, label, placeholder }], idx) => (h("label", { style: Styles.Label, key: idx }, - label ? `${label}: ` : '', - h("input", { ref: idx === 0 ? firstFieldRef : undefined, type: type, name: fieldName, autoComplete: "on", style: Styles.Input, autoFocus: true, placeholder: placeholder, value: params[fieldName] || '', onInput: (ev) => { - var _a; - const value = valueTransformer(type, (_a = ev.target) === null || _a === void 0 ? void 0 : _a['value']); - let updatedParams = Object.assign(Object.assign({}, params), { [fieldName]: value }); - setParams(updatedParams); - if (type === 'otp' && (value === null || value === void 0 ? void 0 : value.trim().length) === OTP_LENGTH) { - // Auto-submit when OTP is filled in. - onSubmit(updatedParams); - } - } })))))), - h("div", { style: Styles.ButtonsDiv }, - h(p$1, null, - h("button", { type: "submit", style: Styles.Button, onClick: () => onSubmit(params) }, submitLabel), - cancelLabel && (h("button", { style: Styles.Button, onClick: onCancel }, cancelLabel)))))); -} -function valueTransformer(type, value) { - switch (type) { - case 'email': - return value.toLowerCase(); - case 'otp': - return value.toUpperCase(); - default: - return value; - } -} - -class LoginGui extends d$1 { - constructor(props) { - super(props); - this.observer = (userInteraction) => this.setState({ userInteraction }); - this.state = { userInteraction: undefined }; - } - componentDidMount() { - this.subscription = (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(this.props.db.cloud.userInteraction).subscribe(this.observer); - } - componentWillUnmount() { - if (this.subscription) { - this.subscription.unsubscribe(); - delete this.subscription; - } - } - render(props, { userInteraction }) { - if (!userInteraction) - return null; - //if (props.db.cloud.userInteraction.observers.length > 1) return null; // Someone else subscribes. - return h(LoginDialog, Object.assign({}, userInteraction)); - } -} -function setupDefaultGUI(db) { - let closed = false; - const el = document.createElement('div'); - if (document.body) { - document.body.appendChild(el); - P(h(LoginGui, { db: db.vip }), el); - } - else { - addEventListener('DOMContentLoaded', () => { - if (!closed) { - document.body.appendChild(el); - P(h(LoginGui, { db: db.vip }), el); - } - }); - } - return { - unsubscribe() { - try { - el.remove(); - } - catch (_a) { } - closed = true; - }, - get closed() { - return closed; - } - }; -} - -function associate(factory) { - const wm = new WeakMap(); - return (x) => { - let rv = wm.get(x); - if (!rv) { - rv = factory(x); - wm.set(x, rv); - } - return rv; - }; -} - -const getCurrentUserEmitter = associate((db) => new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(UNAUTHORIZED_USER)); - -function computeSyncState(db) { - let _prevStatus = db.cloud.webSocketStatus.value; - const lazyWebSocketStatus = db.cloud.webSocketStatus.pipe(switchMap((status) => { - const prevStatus = _prevStatus; - _prevStatus = status; - const rv = (0,rxjs__WEBPACK_IMPORTED_MODULE_7__.of)(status); - switch (status) { - // A normal scenario is that the WS reconnects and falls shortly in disconnected-->connection-->connected. - // Don't distract user with this unless these things take more time than normal: - // Only show disconnected if disconnected more than 500ms, or if we can - // see that the user is indeed not active. - case 'disconnected': - return userIsActive.value ? rv.pipe(debounceTime(500)) : rv; - // Only show connecting if previous state was 'not-started' or 'error', or if - // the time it takes to connect goes beyond 4 seconds. - case 'connecting': - return prevStatus === 'not-started' || prevStatus === 'error' - ? rv - : rv.pipe(debounceTime(4000)); - default: - return rv; - } - })); - return (0,rxjs__WEBPACK_IMPORTED_MODULE_12__.combineLatest)([ - lazyWebSocketStatus, - db.syncStateChangedEvent.pipe(startWith({ phase: 'initial' })), - getCurrentUserEmitter(db.dx._novip), - userIsReallyActive - ]).pipe(map(([status, syncState, user, userIsActive]) => { - var _a; - if (((_a = user.license) === null || _a === void 0 ? void 0 : _a.status) && user.license.status !== 'ok') { - return { - phase: 'offline', - status: 'offline', - license: user.license.status - }; - } - let { phase, error, progress } = syncState; - let adjustedStatus = status; - if (phase === 'error') { - // Let users only rely on the status property to display an icon. - // If there's an error in the sync phase, let it show on that - // status icon also. - adjustedStatus = 'error'; - } - if (status === 'not-started') { - // If websocket isn't yet connected becase we're doing - // the startup sync, let the icon show the symbol for connecting. - if (phase === 'pushing' || phase === 'pulling') { - adjustedStatus = 'connecting'; - } - } - const previousPhase = db.cloud.syncState.value.phase; - //const previousStatus = db.cloud.syncState.value.status; - if (previousPhase === 'error' && (syncState.phase === 'pushing' || syncState.phase === 'pulling')) { - // We were in an errored state but is now doing sync. Show "connecting" icon. - adjustedStatus = 'connecting'; - } - /*if (syncState.phase === 'in-sync' && adjustedStatus === 'connecting') { - adjustedStatus = 'connected'; - }*/ - if (!userIsActive) { - adjustedStatus = 'disconnected'; - } - const retState = { - phase, - error, - progress, - status: isOnline ? adjustedStatus : 'offline', - license: 'ok' - }; - return retState; - })); -} - -function createSharedValueObservable(o, defaultValue) { - let currentValue = defaultValue; - let shared = (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)(o).pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_13__.map)((x) => (currentValue = x)), (0,rxjs__WEBPACK_IMPORTED_MODULE_14__.share)({ resetOnRefCountZero: () => (0,rxjs__WEBPACK_IMPORTED_MODULE_15__.timer)(1000) })); - const rv = new rxjs__WEBPACK_IMPORTED_MODULE_4__.Observable((observer) => { - let didEmit = false; - const subscription = shared.subscribe({ - next(value) { - didEmit = true; - observer.next(value); - }, - error(error) { - observer.error(error); - }, - complete() { - observer.complete(); - } - }); - if (!didEmit && !subscription.closed) { - observer.next(currentValue); - } - return subscription; - }); - rv.getValue = () => currentValue; - return rv; -} - -const getGlobalRolesObservable = associate((db) => { - return createSharedValueObservable((0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => db.roles - .where({ realmId: 'rlm-public' }) - .toArray() - .then((roles) => { - const rv = {}; - for (const role of roles - .slice() - .sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))) { - rv[role.name] = role; - } - return rv; - })), {}); -}); - -const getInternalAccessControlObservable = associate((db) => { - return createSharedValueObservable(getCurrentUserEmitter(db._novip).pipe(switchMap((currentUser) => (0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => db.transaction('r', 'realms', 'members', () => Promise.all([ - db.members.where({ userId: currentUser.userId }).toArray(), - db.realms.toArray(), - currentUser.userId, - ]).then(([selfMembers, realms, userId]) => { - //console.debug(`PERMS: Result from liveQUery():`, JSON.stringify({selfMembers, realms, userId}, null, 2)) - return { selfMembers, realms, userId }; - }))))), { - selfMembers: [], - realms: [], - get userId() { - return db.cloud.currentUserId; - }, - }); - /* let refCount = 0; - return new Observable(observer => { - const subscription = o.subscribe(observer); - console.debug ('PERMS subscribe', ++refCount); - return { - unsubscribe() { - console.debug ('PERMS unsubscribe', --refCount); - subscription.unsubscribe(); - } - } - })*/ -}); - -function mapValueObservable(o, mapper) { - let currentValue; - const rv = o.pipe((0,rxjs__WEBPACK_IMPORTED_MODULE_13__.map)((x) => (currentValue = mapper(x)))); - rv.getValue = () => currentValue !== undefined - ? currentValue - : (currentValue = mapper(o.getValue())); - return rv; -} - -// TODO: Move to dexie-cloud-common -function mergePermissions(...permissions) { - if (permissions.length === 0) - return {}; - const reduced = permissions.reduce((result, next) => { - const ret = Object.assign({}, result); - for (const [verb, rights] of Object.entries(next)) { - if (verb in ret && ret[verb]) { - if (ret[verb] === '*') - continue; - if (rights === '*') { - ret[verb] = '*'; - } - else if (Array.isArray(rights) && Array.isArray(ret[verb])) { - // Both are arrays (verb is 'add' or 'manage') - const r = ret; - const retVerb = r[verb]; // "!" because Array.isArray(ret[verb]) - r[verb] = [...new Set([...retVerb, ...rights])]; - } - else if (typeof rights === 'object' && - rights && - typeof ret[verb] === 'object') { - // Both are objects (verb is 'update') - const mergedRights = ret[verb]; // because we've checked that typeof ret[verb] === 'object' and earlier that not ret[verb] === '*'. - for (const [tableName, tableRights] of Object.entries(rights)) { - if (mergedRights[tableName] === '*') - continue; - if (tableRights === '*') { - mergedRights[tableName] = '*'; - } - else if (Array.isArray(mergedRights[tableName]) && - Array.isArray(tableRights)) { - mergedRights[tableName] = [ - ...new Set([...mergedRights[tableName], ...tableRights]), - ]; - } - } - } - } - else { - /* This compiles without type assertions. Keeping the comment to - explain why we do tsignore on the next statement. - if (verb === "add") { - ret[verb] = next[verb]; - } else if (verb === "update") { - ret[verb] = next[verb]; - } else if (verb === "manage") { - ret[verb] = next[verb]; - } else { - ret[verb] = next[verb]; - } - */ - //@ts-ignore - ret[verb] = next[verb]; - } - } - return ret; - }); - return reduced; -} - -const getPermissionsLookupObservable = associate((db) => { - const o = createSharedValueObservable((0,rxjs__WEBPACK_IMPORTED_MODULE_12__.combineLatest)([ - getInternalAccessControlObservable(db._novip), - getGlobalRolesObservable(db._novip), - ]).pipe(map(([{ selfMembers, realms, userId }, globalRoles]) => ({ - selfMembers, - realms, - userId, - globalRoles, - }))), { - selfMembers: [], - realms: [], - userId: UNAUTHORIZED_USER.userId, - globalRoles: {}, - }); - return mapValueObservable(o, ({ selfMembers, realms, userId, globalRoles }) => { - const rv = realms - .map((realm) => { - const selfRealmMembers = selfMembers.filter((m) => m.realmId === realm.realmId); - const directPermissionSets = selfRealmMembers - .map((m) => m.permissions) - .filter((p) => p); - const rolePermissionSets = flatten(selfRealmMembers.map((m) => m.roles).filter((roleName) => roleName)) - .map((role) => globalRoles[role]) - .filter((role) => role) - .map((role) => role.permissions); - return Object.assign(Object.assign({}, realm), { permissions: realm.owner === userId - ? { manage: '*' } - : mergePermissions(...directPermissionSets, ...rolePermissionSets) }); - }) - .reduce((p, c) => (Object.assign(Object.assign({}, p), { [c.realmId]: c })), { - [userId]: { - realmId: userId, - owner: userId, - name: userId, - permissions: { manage: '*' }, - }, - }); - return rv; - }); -}); - -class PermissionChecker { - constructor(permissions, tableName, isOwner) { - this.permissions = permissions || {}; - this.tableName = tableName; - this.isOwner = isOwner; - } - add(...tableNames) { - var _a; - // If user can manage the whole realm, return true. - if (this.permissions.manage === '*') - return true; - // If user can manage given table in realm, return true - if ((_a = this.permissions.manage) === null || _a === void 0 ? void 0 : _a.includes(this.tableName)) - return true; - // If user can add any type, return true - if (this.permissions.add === '*') - return true; - // If user can add objects into given table names in the realm, return true - if (tableNames.every((tableName) => { var _a; return (_a = this.permissions.add) === null || _a === void 0 ? void 0 : _a.includes(tableName); })) { - return true; - } - return false; - } - update(...props) { - var _a, _b; - // If user is owner of this object, or if user can manage the whole realm, return true. - if (this.isOwner || this.permissions.manage === '*') - return true; - // If user can manage given table in realm, return true - if ((_a = this.permissions.manage) === null || _a === void 0 ? void 0 : _a.includes(this.tableName)) - return true; - // If user can update any prop in any table in this realm, return true unless - // it regards to ownership change: - if (this.permissions.update === '*') { - return props.every((prop) => prop !== 'owner'); - } - const tablePermissions = (_b = this.permissions.update) === null || _b === void 0 ? void 0 : _b[this.tableName]; - // If user can update any prop in table and realm, return true unless - // accessing special props owner or realmId - if (tablePermissions === '*') - return props.every((prop) => prop !== 'owner'); - // Explicitely listed properties to allow updates on: - return props.every((prop) => tablePermissions === null || tablePermissions === void 0 ? void 0 : tablePermissions.some((permittedProp) => permittedProp === prop || (permittedProp === '*' && prop !== 'owner'))); - } - delete() { - var _a; - // If user is owner of this object, or if user can manage the whole realm, return true. - if (this.isOwner || this.permissions.manage === '*') - return true; - // If user can manage given table in realm, return true - if ((_a = this.permissions.manage) === null || _a === void 0 ? void 0 : _a.includes(this.tableName)) - return true; - return false; - } -} - -function permissions(dexie, obj, tableName) { - if (!obj) - throw new TypeError(`Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.`); - const { owner, realmId } = obj; - if (!tableName) { - if (typeof obj.table !== 'function') { - throw new TypeError(`Missing 'table' argument to permissions and table could not be extracted from entity`); - } - tableName = obj.table(); - } - const source = getPermissionsLookupObservable(dexie); - const mapper = (permissionsLookup) => { - // If realmId is undefined, it can be due to that the object is not yet syncified - it exists - // locally only as the user might not yet be authenticated. This is ok and we shall treat it - // as if the realmId is dexie.cloud.currentUserId (which is "unauthorized" by the way) - const realm = permissionsLookup[realmId || dexie.cloud.currentUserId]; - if (!realm) - return new PermissionChecker({}, tableName, !owner || owner === dexie.cloud.currentUserId); - return new PermissionChecker(realm.permissions, tableName, realmId === undefined || realmId === dexie.cloud.currentUserId || owner === dexie.cloud.currentUserId); - }; - const o = source.pipe(map(mapper)); - o.getValue = () => mapper(source.getValue()); - return o; -} - -const getInvitesObservable = associate((db) => { - const membersByEmail = getCurrentUserEmitter(db._novip).pipe(switchMap((currentUser) => (0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => db.members.where({ email: currentUser.email || '' }).toArray()))); - const permissions = getPermissionsLookupObservable(db._novip); - const accessControl = getInternalAccessControlObservable(db._novip); - return createSharedValueObservable((0,rxjs__WEBPACK_IMPORTED_MODULE_12__.combineLatest)([membersByEmail, accessControl, permissions]).pipe(map(([membersByEmail, accessControl, realmLookup]) => { - const reducer = (result, m) => (Object.assign(Object.assign({}, result), { [m.id]: Object.assign(Object.assign({}, m), { realm: realmLookup[m.realmId] }) })); - const emailMembersById = membersByEmail.reduce(reducer, {}); - const membersById = accessControl.selfMembers.reduce(reducer, emailMembersById); - return Object.values(membersById) - .filter((invite) => !invite.accepted) - .map((invite) => (Object.assign(Object.assign({}, invite), { accept() { - return __awaiter(this, void 0, void 0, function* () { - yield db.members.update(invite.id, { accepted: new Date() }); - }); - }, - reject() { - return __awaiter(this, void 0, void 0, function* () { - yield db.members.update(invite.id, { rejected: new Date() }); - }); - } }))); - })), []); -}); - -function getTiedRealmId(objectId) { - return 'rlm~' + objectId; -} -function getTiedObjectId(realmId) { - return realmId.startsWith('rlm~') ? realmId.substr(4) : null; -} - -const DEFAULT_OPTIONS = { - nameSuffix: true, -}; -function dexieCloud(dexie) { - const origIdbName = dexie.name; - // - // - // - const currentUserEmitter = getCurrentUserEmitter(dexie); - const subscriptions = []; - let configuredProgramatically = false; - // local sync worker - used when there's no service worker. - let localSyncWorker = null; - dexie.on('ready', (dexie) => __awaiter(this, void 0, void 0, function* () { - try { - yield onDbReady(dexie); - } - catch (error) { - console.error(error); - // Make sure to succeed with database open even if network is down. - } - }), true // true = sticky - ); - /** Void starting subscribers after a close has happened. */ - let closed = false; - function throwIfClosed() { - if (closed) - throw new dexie__WEBPACK_IMPORTED_MODULE_0__["default"].DatabaseClosedError(); - } - dbOnClosed(dexie, () => { - subscriptions.forEach((subscription) => subscription.unsubscribe()); - closed = true; - localSyncWorker && localSyncWorker.stop(); - localSyncWorker = null; - currentUserEmitter.next(UNAUTHORIZED_USER); - }); - const syncComplete = new rxjs__WEBPACK_IMPORTED_MODULE_6__.Subject(); - dexie.cloud = { - // @ts-ignore - version: "4.0.2", - options: Object.assign({}, DEFAULT_OPTIONS), - schema: null, - get currentUserId() { - return currentUserEmitter.value.userId || UNAUTHORIZED_USER.userId; - }, - currentUser: currentUserEmitter, - syncState: new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject({ - phase: 'initial', - status: 'not-started', - }), - events: { - syncComplete, - }, - persistedSyncState: new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(undefined), - userInteraction: new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject(undefined), - webSocketStatus: new rxjs__WEBPACK_IMPORTED_MODULE_5__.BehaviorSubject('not-started'), - login(hint) { - return __awaiter(this, void 0, void 0, function* () { - const db = DexieCloudDB(dexie); - yield db.cloud.sync(); - yield login(db, hint); - }); - }, - invites: getInvitesObservable(dexie), - roles: getGlobalRolesObservable(dexie), - configure(options) { - options = dexie.cloud.options = Object.assign(Object.assign({}, dexie.cloud.options), options); - configuredProgramatically = true; - if (options.databaseUrl && options.nameSuffix) { - // @ts-ignore - dexie.name = `${origIdbName}-${getDbNameFromDbUrl(options.databaseUrl)}`; - DexieCloudDB(dexie).reconfigure(); // Update observable from new dexie.name - } - updateSchemaFromOptions(dexie.cloud.schema, dexie.cloud.options); - }, - logout({ force } = {}) { - return __awaiter(this, void 0, void 0, function* () { - force - ? yield _logout(DexieCloudDB(dexie), { deleteUnsyncedData: true }) - : yield logout(DexieCloudDB(dexie)); - }); - }, - sync({ wait, purpose } = { wait: true, purpose: 'push' }) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (wait === undefined) - wait = true; - const db = DexieCloudDB(dexie); - const licenseStatus = ((_a = db.cloud.currentUser.value.license) === null || _a === void 0 ? void 0 : _a.status) || 'ok'; - if (licenseStatus !== 'ok') { - // Refresh access token to check for updated license - yield loadAccessToken(db); - } - if (purpose === 'pull') { - const syncState = db.cloud.persistedSyncState.value; - triggerSync(db, purpose); - if (wait) { - const newSyncState = yield db.cloud.persistedSyncState - .pipe(filter((newSyncState) => (newSyncState === null || newSyncState === void 0 ? void 0 : newSyncState.timestamp) != null && - (!syncState || newSyncState.timestamp > syncState.timestamp)), take(1)) - .toPromise(); - if (newSyncState === null || newSyncState === void 0 ? void 0 : newSyncState.error) { - throw new Error(`Sync error: ` + newSyncState.error); - } - } - } - else if (yield isSyncNeeded(db)) { - const syncState = db.cloud.persistedSyncState.value; - triggerSync(db, purpose); - if (wait) { - console.debug('db.cloud.login() is waiting for sync completion...'); - yield (0,rxjs__WEBPACK_IMPORTED_MODULE_2__.from)((0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => __awaiter(this, void 0, void 0, function* () { - const syncNeeded = yield isSyncNeeded(db); - const newSyncState = yield db.getPersistedSyncState(); - if ((newSyncState === null || newSyncState === void 0 ? void 0 : newSyncState.timestamp) !== (syncState === null || syncState === void 0 ? void 0 : syncState.timestamp) && - (newSyncState === null || newSyncState === void 0 ? void 0 : newSyncState.error)) - throw new Error(`Sync error: ` + newSyncState.error); - return syncNeeded; - }))) - .pipe(filter((isNeeded) => !isNeeded), take(1)) - .toPromise(); - console.debug('Done waiting for sync completion because we have nothing to push anymore'); - } - } - }); - }, - permissions(obj, tableName) { - return permissions(dexie._novip, obj, tableName); - }, - }; - dexie.Version.prototype['_parseStoresSpec'] = dexie__WEBPACK_IMPORTED_MODULE_0__["default"].override(dexie.Version.prototype['_parseStoresSpec'], (origFunc) => overrideParseStoresSpec(origFunc, dexie)); - dexie.Table.prototype.newId = function ({ colocateWith } = {}) { - const shardKey = colocateWith && colocateWith.substr(colocateWith.length - 3); - return generateKey(dexie.cloud.schema[this.name].idPrefix || '', shardKey); - }; - dexie.Table.prototype.idPrefix = function () { - var _a, _b; - return ((_b = (_a = this.db.cloud.schema) === null || _a === void 0 ? void 0 : _a[this.name]) === null || _b === void 0 ? void 0 : _b.idPrefix) || ''; - }; - dexie.use(createMutationTrackingMiddleware({ - currentUserObservable: dexie.cloud.currentUser, - db: DexieCloudDB(dexie), - })); - dexie.use(createImplicitPropSetterMiddleware(DexieCloudDB(dexie))); - dexie.use(createIdGenerationMiddleware(DexieCloudDB(dexie))); - function onDbReady(dexie) { - var _a, _b, _c, _d, _e, _f, _g; - return __awaiter(this, void 0, void 0, function* () { - closed = false; // As Dexie calls us, we are not closed anymore. Maybe reopened? Remember db.ready event is registered with sticky flag! - const db = DexieCloudDB(dexie); - // Setup default GUI: - if (typeof window !== 'undefined' && typeof document !== 'undefined') { - if (!((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.customLoginGui)) { - subscriptions.push(setupDefaultGUI(dexie)); - } - } - if (!db.cloud.isServiceWorkerDB) { - subscriptions.push(computeSyncState(db).subscribe(dexie.cloud.syncState)); - } - // Forward db.syncCompleteEvent to be publicly consumable via db.cloud.events.syncComplete: - subscriptions.push(db.syncCompleteEvent.subscribe(syncComplete)); - //verifyConfig(db.cloud.options); Not needed (yet at least!) - // Verify the user has allowed version increment. - if (!db.tables.every((table) => table.core)) { - throwVersionIncrementNeeded(); - } - const swRegistrations = 'serviceWorker' in navigator - ? yield navigator.serviceWorker.getRegistrations() - : []; - const initiallySynced = yield db.transaction('rw', db.$syncState, () => __awaiter(this, void 0, void 0, function* () { - var _h, _j; - const { options, schema } = db.cloud; - const [persistedOptions, persistedSchema, persistedSyncState] = yield Promise.all([ - db.getOptions(), - db.getSchema(), - db.getPersistedSyncState(), - ]); - if (!configuredProgramatically) { - // Options not specified programatically (use case for SW!) - // Take persisted options: - db.cloud.options = persistedOptions || null; - } - else if (!persistedOptions || - JSON.stringify(persistedOptions) !== JSON.stringify(options)) { - // Update persisted options: - if (!options) - throw new Error(`Internal error`); // options cannot be null if configuredProgramatically is set. - const newPersistedOptions = Object.assign({}, options); - delete newPersistedOptions.fetchTokens; - yield db.$syncState.put(newPersistedOptions, 'options'); - } - if (((_h = db.cloud.options) === null || _h === void 0 ? void 0 : _h.tryUseServiceWorker) && - 'serviceWorker' in navigator && - swRegistrations.length > 0 && - !DISABLE_SERVICEWORKER_STRATEGY) { - // * Configured for using service worker if available. - // * Browser supports service workers - // * There are at least one service worker registration - console.debug('Dexie Cloud Addon: Using service worker'); - db.cloud.usingServiceWorker = true; - } - else { - // Not configured for using service worker or no service worker - // registration exists. Don't rely on service worker to do any job. - // Use LocalSyncWorker instead. - if (((_j = db.cloud.options) === null || _j === void 0 ? void 0 : _j.tryUseServiceWorker) && - !db.cloud.isServiceWorkerDB) { - console.debug('dexie-cloud-addon: Not using service worker.', swRegistrations.length === 0 - ? 'No SW registrations found.' - : 'serviceWorker' in navigator && DISABLE_SERVICEWORKER_STRATEGY - ? 'Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.' - : 'navigator.serviceWorker not present'); - } - db.cloud.usingServiceWorker = false; - } - updateSchemaFromOptions(schema, db.cloud.options); - updateSchemaFromOptions(persistedSchema, db.cloud.options); - if (!schema) { - // Database opened dynamically (use case for SW!) - // Take persisted schema: - db.cloud.schema = persistedSchema || null; - } - else if (!persistedSchema || - JSON.stringify(persistedSchema) !== JSON.stringify(schema)) { - // Update persisted schema (but don't overwrite table prefixes) - const newPersistedSchema = persistedSchema || {}; - for (const [table, tblSchema] of Object.entries(schema)) { - const newTblSchema = newPersistedSchema[table]; - if (!newTblSchema) { - newPersistedSchema[table] = Object.assign({}, tblSchema); - } - else { - newTblSchema.markedForSync = tblSchema.markedForSync; - tblSchema.deleted = newTblSchema.deleted; - newTblSchema.generatedGlobalId = tblSchema.generatedGlobalId; - } - } - yield db.$syncState.put(newPersistedSchema, 'schema'); - // Make sure persisted table prefixes are being used instead of computed ones: - // Let's assign all props as the newPersistedSchems should be what we should be working with. - Object.assign(schema, newPersistedSchema); - } - return persistedSyncState === null || persistedSyncState === void 0 ? void 0 : persistedSyncState.initiallySynced; - })); - if (initiallySynced) { - db.setInitiallySynced(true); - } - verifySchema(db); - if (((_b = db.cloud.options) === null || _b === void 0 ? void 0 : _b.databaseUrl) && !initiallySynced) { - yield performInitialSync(db, db.cloud.options, db.cloud.schema); - db.setInitiallySynced(true); - } - // Manage CurrentUser observable: - throwIfClosed(); - if (!db.cloud.isServiceWorkerDB) { - subscriptions.push((0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => db.getCurrentUser()).subscribe(currentUserEmitter)); - // Manage PersistendSyncState observable: - subscriptions.push((0,dexie__WEBPACK_IMPORTED_MODULE_0__.liveQuery)(() => db.getPersistedSyncState()).subscribe(db.cloud.persistedSyncState)); - // Wait till currentUser and persistedSyncState gets populated - // with things from the database and not just the default values. - // This is so that when db.open() completes, user should be safe - // to subscribe to these observables and get actual data. - yield (0,rxjs__WEBPACK_IMPORTED_MODULE_12__.combineLatest)([ - currentUserEmitter.pipe(skip(1), take(1)), - db.cloud.persistedSyncState.pipe(skip(1), take(1)), - ]).toPromise(); - } - // HERE: If requireAuth, do athentication now. - let changedUser = false; - if ((_c = db.cloud.options) === null || _c === void 0 ? void 0 : _c.requireAuth) { - changedUser = yield login(db); - } - if (localSyncWorker) - localSyncWorker.stop(); - localSyncWorker = null; - throwIfClosed(); - if (db.cloud.usingServiceWorker && ((_d = db.cloud.options) === null || _d === void 0 ? void 0 : _d.databaseUrl)) { - registerSyncEvent(db, changedUser ? 'pull' : 'push').catch(() => { }); - registerPeriodicSyncEvent(db).catch(() => { }); - } - else if (((_e = db.cloud.options) === null || _e === void 0 ? void 0 : _e.databaseUrl) && - db.cloud.schema && - !db.cloud.isServiceWorkerDB) { - // There's no SW. Start SyncWorker instead. - localSyncWorker = LocalSyncWorker(db, db.cloud.options, db.cloud.schema); - localSyncWorker.start(); - triggerSync(db, changedUser ? 'pull' : 'push'); - } - // Listen to online event and do sync. - throwIfClosed(); - if (!db.cloud.isServiceWorkerDB) { - subscriptions.push((0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(self, 'online').subscribe(() => { - console.debug('online!'); - db.syncStateChangedEvent.next({ - phase: 'not-in-sync', - }); - if (!isEagerSyncDisabled(db)) { - triggerSync(db, 'push'); - } - }), (0,rxjs__WEBPACK_IMPORTED_MODULE_8__.fromEvent)(self, 'offline').subscribe(() => { - console.debug('offline!'); - db.syncStateChangedEvent.next({ - phase: 'offline', - }); - })); - } - // Connect WebSocket unless we - if (((_f = db.cloud.options) === null || _f === void 0 ? void 0 : _f.databaseUrl) && - !((_g = db.cloud.options) === null || _g === void 0 ? void 0 : _g.disableWebSocket) && - !IS_SERVICE_WORKER) { - subscriptions.push(connectWebSocket(db)); - } - }); - } -} -// @ts-ignore -dexieCloud.version = "4.0.2"; -dexie__WEBPACK_IMPORTED_MODULE_0__["default"].Cloud = dexieCloud; - - - - -/***/ }), - -/***/ "./node_modules/tslib/tslib.es6.mjs": -/*!******************************************!*\ - !*** ./node_modules/tslib/tslib.es6.mjs ***! - \******************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ __addDisposableResource: () => (/* binding */ __addDisposableResource), -/* harmony export */ __assign: () => (/* binding */ __assign), -/* harmony export */ __asyncDelegator: () => (/* binding */ __asyncDelegator), -/* harmony export */ __asyncGenerator: () => (/* binding */ __asyncGenerator), -/* harmony export */ __asyncValues: () => (/* binding */ __asyncValues), -/* harmony export */ __await: () => (/* binding */ __await), -/* harmony export */ __awaiter: () => (/* binding */ __awaiter), -/* harmony export */ __classPrivateFieldGet: () => (/* binding */ __classPrivateFieldGet), -/* harmony export */ __classPrivateFieldIn: () => (/* binding */ __classPrivateFieldIn), -/* harmony export */ __classPrivateFieldSet: () => (/* binding */ __classPrivateFieldSet), -/* harmony export */ __createBinding: () => (/* binding */ __createBinding), -/* harmony export */ __decorate: () => (/* binding */ __decorate), -/* harmony export */ __disposeResources: () => (/* binding */ __disposeResources), -/* harmony export */ __esDecorate: () => (/* binding */ __esDecorate), -/* harmony export */ __exportStar: () => (/* binding */ __exportStar), -/* harmony export */ __extends: () => (/* binding */ __extends), -/* harmony export */ __generator: () => (/* binding */ __generator), -/* harmony export */ __importDefault: () => (/* binding */ __importDefault), -/* harmony export */ __importStar: () => (/* binding */ __importStar), -/* harmony export */ __makeTemplateObject: () => (/* binding */ __makeTemplateObject), -/* harmony export */ __metadata: () => (/* binding */ __metadata), -/* harmony export */ __param: () => (/* binding */ __param), -/* harmony export */ __propKey: () => (/* binding */ __propKey), -/* harmony export */ __read: () => (/* binding */ __read), -/* harmony export */ __rest: () => (/* binding */ __rest), -/* harmony export */ __runInitializers: () => (/* binding */ __runInitializers), -/* harmony export */ __setFunctionName: () => (/* binding */ __setFunctionName), -/* harmony export */ __spread: () => (/* binding */ __spread), -/* harmony export */ __spreadArray: () => (/* binding */ __spreadArray), -/* harmony export */ __spreadArrays: () => (/* binding */ __spreadArrays), -/* harmony export */ __values: () => (/* binding */ __values), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -}; - -function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -}; - -function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -}; - -function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); -}; - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -var __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); - -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -/** @deprecated */ -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -/** @deprecated */ -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -} - -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} - -function __addDisposableResource(env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; -} - -var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -function __disposeResources(env) { - function fail(e) { - env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - function next() { - while (env.stack.length) { - var rec = env.stack.pop(); - try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - catch (e) { - fail(e); - } - } - if (env.hasError) throw env.error; - } - return next(); -} - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ - __extends, - __assign, - __rest, - __decorate, - __param, - __metadata, - __awaiter, - __generator, - __createBinding, - __exportStar, - __values, - __read, - __spread, - __spreadArrays, - __spreadArray, - __await, - __asyncGenerator, - __asyncDelegator, - __asyncValues, - __makeTemplateObject, - __importStar, - __importDefault, - __classPrivateFieldGet, - __classPrivateFieldSet, - __classPrivateFieldIn, - __addDisposableResource, - __disposeResources, -}); - - -/***/ }), - -/***/ "../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs": -/*!*****************************************************************!*\ - !*** ../../DexieNET/yarn/node_modules/dexie/import-wrapper.mjs ***! - \*****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Dexie: () => (/* binding */ Dexie), -/* harmony export */ Entity: () => (/* binding */ Entity), -/* harmony export */ PropModSymbol: () => (/* binding */ PropModSymbol), -/* harmony export */ PropModification: () => (/* binding */ PropModification), -/* harmony export */ RangeSet: () => (/* binding */ RangeSet), -/* harmony export */ cmp: () => (/* binding */ cmp), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), -/* harmony export */ liveQuery: () => (/* binding */ liveQuery), -/* harmony export */ mergeRanges: () => (/* binding */ mergeRanges), -/* harmony export */ rangesOverlap: () => (/* binding */ rangesOverlap), -/* harmony export */ replacePrefix: () => (/* binding */ replacePrefix) -/* harmony export */ }); -/* harmony import */ var _dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dist/dexie.js */ "../../DexieNET/yarn/node_modules/dexie/dist/dexie.js"); -// Making the module version consumable via require - to prohibit -// multiple occurrancies of the same module in the same app -// (dual package hazard, https://nodejs.org/api/packages.html#dual-package-hazard) - -const DexieSymbol = Symbol.for("Dexie"); -const Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = _dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__); -if (_dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__.semVer !== Dexie.semVer) { - throw new Error(`Two different versions of Dexie loaded in the same app: ${_dist_dexie_js__WEBPACK_IMPORTED_MODULE_0__.semVer} and ${Dexie.semVer}`); -} -const { liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp, Entity, PropModSymbol, PropModification, replacePrefix } = Dexie; - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Dexie); - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/global */ -/******/ (() => { -/******/ __webpack_require__.g = (function() { -/******/ if (typeof globalThis === 'object') return globalThis; -/******/ try { -/******/ return this || new Function('return this')(); -/******/ } catch (e) { -/******/ if (typeof window === 'object') return window; -/******/ } -/******/ })(); -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk. -(() => { -/*!******************************!*\ - !*** ./src/dexieCloudNET.ts ***! - \******************************/ -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AbortCurrentTransaction: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.AbortCurrentTransaction), -/* harmony export */ AbortTransaction: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.AbortTransaction), -/* harmony export */ AcceptInvite: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.AcceptInvite), -/* harmony export */ AcceptInviteMember: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.AcceptInviteMember), -/* harmony export */ AddByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.AddByteArray), -/* harmony export */ AddOnVersion: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.AddOnVersion), -/* harmony export */ BulkAddByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.BulkAddByteArray), -/* harmony export */ BulkPutByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.BulkPutByteArray), -/* harmony export */ ClearInviteMember: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.ClearInviteMember), -/* harmony export */ ClearInvites: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.ClearInvites), -/* harmony export */ ClearPermissionChecker: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.ClearPermissionChecker), -/* harmony export */ ClearUserInteraction: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.ClearUserInteraction), -/* harmony export */ CloudDB: () => (/* reexport safe */ _dexieCloudNETBase__WEBPACK_IMPORTED_MODULE_0__.CloudDB), -/* harmony export */ CollectionEach: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionEach), -/* harmony export */ CollectionEachKey: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionEachKey), -/* harmony export */ CollectionEachPrimaryKey: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionEachPrimaryKey), -/* harmony export */ CollectionEachUniqueKey: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionEachUniqueKey), -/* harmony export */ CollectionFilter: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionFilter), -/* harmony export */ CollectionKeysByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionKeysByteArray), -/* harmony export */ CollectionModify: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionModify), -/* harmony export */ CollectionModifyReplacePrefix: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionModifyReplacePrefix), -/* harmony export */ CollectionPrimarykeysByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionPrimarykeysByteArray), -/* harmony export */ CollectionUntil: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CollectionUntil), -/* harmony export */ ConfigureCloud: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.ConfigureCloud), -/* harmony export */ Create: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Create), -/* harmony export */ CreateCloud: () => (/* reexport safe */ _dexieCloudNETBase__WEBPACK_IMPORTED_MODULE_0__.CreateCloud), -/* harmony export */ CurrentTransaction: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.CurrentTransaction), -/* harmony export */ CurrentUserId: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.CurrentUserId), -/* harmony export */ DB: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.DB), -/* harmony export */ Delete: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Delete), -/* harmony export */ DotNetObservable: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.DotNetObservable), -/* harmony export */ GetTiedRealmID: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.GetTiedRealmID), -/* harmony export */ InitStoragePersistence: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.InitStoragePersistence), -/* harmony export */ LiveQuery: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.LiveQuery), -/* harmony export */ LiveQuerySubscribe: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.LiveQuerySubscribe), -/* harmony export */ LiveQueryUnsubscribe: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.LiveQueryUnsubscribe), -/* harmony export */ Logout: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.Logout), -/* harmony export */ Modify: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Modify), -/* harmony export */ Name: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Name), -/* harmony export */ OnCancelUserInteraction: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.OnCancelUserInteraction), -/* harmony export */ OnSubmitUserInteraction: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.OnSubmitUserInteraction), -/* harmony export */ Options: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.Options), -/* harmony export */ PermissionCheckerAdd: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.PermissionCheckerAdd), -/* harmony export */ PermissionCheckerDelete: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.PermissionCheckerDelete), -/* harmony export */ PermissionCheckerUpdate: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.PermissionCheckerUpdate), -/* harmony export */ Persist: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Persist), -/* harmony export */ PutByteArray: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.PutByteArray), -/* harmony export */ RejectInvite: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.RejectInvite), -/* harmony export */ RejectInviteMember: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.RejectInviteMember), -/* harmony export */ Schema: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.Schema), -/* harmony export */ ShowEstimatedQuota: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.ShowEstimatedQuota), -/* harmony export */ SubscribeInvites: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeInvites), -/* harmony export */ SubscribePermissionChecker: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribePermissionChecker), -/* harmony export */ SubscribePersistedSyncState: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribePersistedSyncState), -/* harmony export */ SubscribeRoles: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeRoles), -/* harmony export */ SubscribeSyncComplete: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeSyncComplete), -/* harmony export */ SubscribeSyncState: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeSyncState), -/* harmony export */ SubscribeUserInteraction: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeUserInteraction), -/* harmony export */ SubscribeUserLogin: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeUserLogin), -/* harmony export */ SubscribeWebSocketStatus: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.SubscribeWebSocketStatus), -/* harmony export */ Sync: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.Sync), -/* harmony export */ TopLevelTransaction: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.TopLevelTransaction), -/* harmony export */ TopLevelTransactionAsync: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.TopLevelTransactionAsync), -/* harmony export */ TransactioWaitFor: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.TransactioWaitFor), -/* harmony export */ UnSubscribeJSObservable: () => (/* reexport safe */ _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__.UnSubscribeJSObservable), -/* harmony export */ Upgrade: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Upgrade), -/* harmony export */ UserLogin: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.UserLogin), -/* harmony export */ UsingServiceWorker: () => (/* reexport safe */ _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__.UsingServiceWorker), -/* harmony export */ Version: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.Version), -/* harmony export */ iOS: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.iOS), -/* harmony export */ tryPersistWithoutPromtingUser: () => (/* reexport safe */ _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__.tryPersistWithoutPromtingUser) -/* harmony export */ }); -/* harmony import */ var _dexieCloudNETBase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./dexieCloudNETBase */ "./src/dexieCloudNETBase.js"); -/* harmony import */ var _dexieCloudNETCloud__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dexieCloudNETCloud */ "./src/dexieCloudNETCloud.js"); -/* harmony import */ var _dexieCloudNETObservables__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dexieCloudNETObservables */ "./src/dexieCloudNETObservables.js"); -/* harmony import */ var _DexieNET_yarn_src_dexieNET__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../DexieNET/yarn/src/dexieNET */ "../../DexieNET/yarn/src/dexieNET.js"); - - - - - - - - - -})(); - -var __webpack_exports__AbortCurrentTransaction = __webpack_exports__.AbortCurrentTransaction; -var __webpack_exports__AbortTransaction = __webpack_exports__.AbortTransaction; -var __webpack_exports__AcceptInvite = __webpack_exports__.AcceptInvite; -var __webpack_exports__AcceptInviteMember = __webpack_exports__.AcceptInviteMember; -var __webpack_exports__AddByteArray = __webpack_exports__.AddByteArray; -var __webpack_exports__AddOnVersion = __webpack_exports__.AddOnVersion; -var __webpack_exports__BulkAddByteArray = __webpack_exports__.BulkAddByteArray; -var __webpack_exports__BulkPutByteArray = __webpack_exports__.BulkPutByteArray; -var __webpack_exports__ClearInviteMember = __webpack_exports__.ClearInviteMember; -var __webpack_exports__ClearInvites = __webpack_exports__.ClearInvites; -var __webpack_exports__ClearPermissionChecker = __webpack_exports__.ClearPermissionChecker; -var __webpack_exports__ClearUserInteraction = __webpack_exports__.ClearUserInteraction; -var __webpack_exports__CloudDB = __webpack_exports__.CloudDB; -var __webpack_exports__CollectionEach = __webpack_exports__.CollectionEach; -var __webpack_exports__CollectionEachKey = __webpack_exports__.CollectionEachKey; -var __webpack_exports__CollectionEachPrimaryKey = __webpack_exports__.CollectionEachPrimaryKey; -var __webpack_exports__CollectionEachUniqueKey = __webpack_exports__.CollectionEachUniqueKey; -var __webpack_exports__CollectionFilter = __webpack_exports__.CollectionFilter; -var __webpack_exports__CollectionKeysByteArray = __webpack_exports__.CollectionKeysByteArray; -var __webpack_exports__CollectionModify = __webpack_exports__.CollectionModify; -var __webpack_exports__CollectionModifyReplacePrefix = __webpack_exports__.CollectionModifyReplacePrefix; -var __webpack_exports__CollectionPrimarykeysByteArray = __webpack_exports__.CollectionPrimarykeysByteArray; -var __webpack_exports__CollectionUntil = __webpack_exports__.CollectionUntil; -var __webpack_exports__ConfigureCloud = __webpack_exports__.ConfigureCloud; -var __webpack_exports__Create = __webpack_exports__.Create; -var __webpack_exports__CreateCloud = __webpack_exports__.CreateCloud; -var __webpack_exports__CurrentTransaction = __webpack_exports__.CurrentTransaction; -var __webpack_exports__CurrentUserId = __webpack_exports__.CurrentUserId; -var __webpack_exports__DB = __webpack_exports__.DB; -var __webpack_exports__Delete = __webpack_exports__.Delete; -var __webpack_exports__DotNetObservable = __webpack_exports__.DotNetObservable; -var __webpack_exports__GetTiedRealmID = __webpack_exports__.GetTiedRealmID; -var __webpack_exports__InitStoragePersistence = __webpack_exports__.InitStoragePersistence; -var __webpack_exports__LiveQuery = __webpack_exports__.LiveQuery; -var __webpack_exports__LiveQuerySubscribe = __webpack_exports__.LiveQuerySubscribe; -var __webpack_exports__LiveQueryUnsubscribe = __webpack_exports__.LiveQueryUnsubscribe; -var __webpack_exports__Logout = __webpack_exports__.Logout; -var __webpack_exports__Modify = __webpack_exports__.Modify; -var __webpack_exports__Name = __webpack_exports__.Name; -var __webpack_exports__OnCancelUserInteraction = __webpack_exports__.OnCancelUserInteraction; -var __webpack_exports__OnSubmitUserInteraction = __webpack_exports__.OnSubmitUserInteraction; -var __webpack_exports__Options = __webpack_exports__.Options; -var __webpack_exports__PermissionCheckerAdd = __webpack_exports__.PermissionCheckerAdd; -var __webpack_exports__PermissionCheckerDelete = __webpack_exports__.PermissionCheckerDelete; -var __webpack_exports__PermissionCheckerUpdate = __webpack_exports__.PermissionCheckerUpdate; -var __webpack_exports__Persist = __webpack_exports__.Persist; -var __webpack_exports__PutByteArray = __webpack_exports__.PutByteArray; -var __webpack_exports__RejectInvite = __webpack_exports__.RejectInvite; -var __webpack_exports__RejectInviteMember = __webpack_exports__.RejectInviteMember; -var __webpack_exports__Schema = __webpack_exports__.Schema; -var __webpack_exports__ShowEstimatedQuota = __webpack_exports__.ShowEstimatedQuota; -var __webpack_exports__SubscribeInvites = __webpack_exports__.SubscribeInvites; -var __webpack_exports__SubscribePermissionChecker = __webpack_exports__.SubscribePermissionChecker; -var __webpack_exports__SubscribePersistedSyncState = __webpack_exports__.SubscribePersistedSyncState; -var __webpack_exports__SubscribeRoles = __webpack_exports__.SubscribeRoles; -var __webpack_exports__SubscribeSyncComplete = __webpack_exports__.SubscribeSyncComplete; -var __webpack_exports__SubscribeSyncState = __webpack_exports__.SubscribeSyncState; -var __webpack_exports__SubscribeUserInteraction = __webpack_exports__.SubscribeUserInteraction; -var __webpack_exports__SubscribeUserLogin = __webpack_exports__.SubscribeUserLogin; -var __webpack_exports__SubscribeWebSocketStatus = __webpack_exports__.SubscribeWebSocketStatus; -var __webpack_exports__Sync = __webpack_exports__.Sync; -var __webpack_exports__TopLevelTransaction = __webpack_exports__.TopLevelTransaction; -var __webpack_exports__TopLevelTransactionAsync = __webpack_exports__.TopLevelTransactionAsync; -var __webpack_exports__TransactioWaitFor = __webpack_exports__.TransactioWaitFor; -var __webpack_exports__UnSubscribeJSObservable = __webpack_exports__.UnSubscribeJSObservable; -var __webpack_exports__Upgrade = __webpack_exports__.Upgrade; -var __webpack_exports__UserLogin = __webpack_exports__.UserLogin; -var __webpack_exports__UsingServiceWorker = __webpack_exports__.UsingServiceWorker; -var __webpack_exports__Version = __webpack_exports__.Version; -var __webpack_exports__iOS = __webpack_exports__.iOS; -var __webpack_exports__tryPersistWithoutPromtingUser = __webpack_exports__.tryPersistWithoutPromtingUser; -export { __webpack_exports__AbortCurrentTransaction as AbortCurrentTransaction, __webpack_exports__AbortTransaction as AbortTransaction, __webpack_exports__AcceptInvite as AcceptInvite, __webpack_exports__AcceptInviteMember as AcceptInviteMember, __webpack_exports__AddByteArray as AddByteArray, __webpack_exports__AddOnVersion as AddOnVersion, __webpack_exports__BulkAddByteArray as BulkAddByteArray, __webpack_exports__BulkPutByteArray as BulkPutByteArray, __webpack_exports__ClearInviteMember as ClearInviteMember, __webpack_exports__ClearInvites as ClearInvites, __webpack_exports__ClearPermissionChecker as ClearPermissionChecker, __webpack_exports__ClearUserInteraction as ClearUserInteraction, __webpack_exports__CloudDB as CloudDB, __webpack_exports__CollectionEach as CollectionEach, __webpack_exports__CollectionEachKey as CollectionEachKey, __webpack_exports__CollectionEachPrimaryKey as CollectionEachPrimaryKey, __webpack_exports__CollectionEachUniqueKey as CollectionEachUniqueKey, __webpack_exports__CollectionFilter as CollectionFilter, __webpack_exports__CollectionKeysByteArray as CollectionKeysByteArray, __webpack_exports__CollectionModify as CollectionModify, __webpack_exports__CollectionModifyReplacePrefix as CollectionModifyReplacePrefix, __webpack_exports__CollectionPrimarykeysByteArray as CollectionPrimarykeysByteArray, __webpack_exports__CollectionUntil as CollectionUntil, __webpack_exports__ConfigureCloud as ConfigureCloud, __webpack_exports__Create as Create, __webpack_exports__CreateCloud as CreateCloud, __webpack_exports__CurrentTransaction as CurrentTransaction, __webpack_exports__CurrentUserId as CurrentUserId, __webpack_exports__DB as DB, __webpack_exports__Delete as Delete, __webpack_exports__DotNetObservable as DotNetObservable, __webpack_exports__GetTiedRealmID as GetTiedRealmID, __webpack_exports__InitStoragePersistence as InitStoragePersistence, __webpack_exports__LiveQuery as LiveQuery, __webpack_exports__LiveQuerySubscribe as LiveQuerySubscribe, __webpack_exports__LiveQueryUnsubscribe as LiveQueryUnsubscribe, __webpack_exports__Logout as Logout, __webpack_exports__Modify as Modify, __webpack_exports__Name as Name, __webpack_exports__OnCancelUserInteraction as OnCancelUserInteraction, __webpack_exports__OnSubmitUserInteraction as OnSubmitUserInteraction, __webpack_exports__Options as Options, __webpack_exports__PermissionCheckerAdd as PermissionCheckerAdd, __webpack_exports__PermissionCheckerDelete as PermissionCheckerDelete, __webpack_exports__PermissionCheckerUpdate as PermissionCheckerUpdate, __webpack_exports__Persist as Persist, __webpack_exports__PutByteArray as PutByteArray, __webpack_exports__RejectInvite as RejectInvite, __webpack_exports__RejectInviteMember as RejectInviteMember, __webpack_exports__Schema as Schema, __webpack_exports__ShowEstimatedQuota as ShowEstimatedQuota, __webpack_exports__SubscribeInvites as SubscribeInvites, __webpack_exports__SubscribePermissionChecker as SubscribePermissionChecker, __webpack_exports__SubscribePersistedSyncState as SubscribePersistedSyncState, __webpack_exports__SubscribeRoles as SubscribeRoles, __webpack_exports__SubscribeSyncComplete as SubscribeSyncComplete, __webpack_exports__SubscribeSyncState as SubscribeSyncState, __webpack_exports__SubscribeUserInteraction as SubscribeUserInteraction, __webpack_exports__SubscribeUserLogin as SubscribeUserLogin, __webpack_exports__SubscribeWebSocketStatus as SubscribeWebSocketStatus, __webpack_exports__Sync as Sync, __webpack_exports__TopLevelTransaction as TopLevelTransaction, __webpack_exports__TopLevelTransactionAsync as TopLevelTransactionAsync, __webpack_exports__TransactioWaitFor as TransactioWaitFor, __webpack_exports__UnSubscribeJSObservable as UnSubscribeJSObservable, __webpack_exports__Upgrade as Upgrade, __webpack_exports__UserLogin as UserLogin, __webpack_exports__UsingServiceWorker as UsingServiceWorker, __webpack_exports__Version as Version, __webpack_exports__iOS as iOS, __webpack_exports__tryPersistWithoutPromtingUser as tryPersistWithoutPromtingUser }; - -//# sourceMappingURL=dexieCloudNET.js.map \ No newline at end of file diff --git a/DexieCloudNET/yarn/src/dexieCloudNET.js b/DexieCloudNET/yarn/src/dexieCloudNET.js deleted file mode 100644 index d556d0f..0000000 --- a/DexieCloudNET/yarn/src/dexieCloudNET.js +++ /dev/null @@ -1,7 +0,0 @@ -import "./dexieCloudNETBase"; -import "./dexieCloudNETCloud"; -import "./dexieCloudNETObservables"; -export * from "./dexieCloudNETBase"; -export * from "./dexieCloudNETCloud"; -export * from "./dexieCloudNETObservables"; -//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGV4aWVDbG91ZE5FVC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImRleGllQ2xvdWRORVQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxxQkFBcUIsQ0FBQztBQUM3QixPQUFPLHNCQUFzQixDQUFDO0FBQzlCLE9BQU8sNEJBQTRCLENBQUM7QUFDcEMsT0FBTyxxQ0FBcUMsQ0FBQTtBQUU1QyxjQUFjLHFCQUFxQixDQUFDO0FBQ3BDLGNBQWMsc0JBQXNCLENBQUM7QUFDckMsY0FBYyw0QkFBNEIsQ0FBQztBQUMzQyxjQUFjLHFDQUFxQyxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFwiLi9kZXhpZUNsb3VkTkVUQmFzZVwiO1xuaW1wb3J0IFwiLi9kZXhpZUNsb3VkTkVUQ2xvdWRcIjtcbmltcG9ydCBcIi4vZGV4aWVDbG91ZE5FVE9ic2VydmFibGVzXCI7XG5pbXBvcnQgXCIuLi8uLi8uLi9EZXhpZU5FVC95YXJuL3NyYy9kZXhpZU5FVFwiXG5cbmV4cG9ydCAqIGZyb20gXCIuL2RleGllQ2xvdWRORVRCYXNlXCI7XG5leHBvcnQgKiBmcm9tIFwiLi9kZXhpZUNsb3VkTkVUQ2xvdWRcIjtcbmV4cG9ydCAqIGZyb20gXCIuL2RleGllQ2xvdWRORVRPYnNlcnZhYmxlc1wiO1xuZXhwb3J0ICogZnJvbSBcIi4uLy4uLy4uL0RleGllTkVUL3lhcm4vc3JjL2RleGllTkVUXCI7Il19 \ No newline at end of file diff --git a/DexieCloudNET/yarn/src/dexieCloudNET.ts b/DexieCloudNET/yarn/src/dexieCloudNET.ts index 8e702f5..c03f0ac 100644 --- a/DexieCloudNET/yarn/src/dexieCloudNET.ts +++ b/DexieCloudNET/yarn/src/dexieCloudNET.ts @@ -1,9 +1,21 @@ import "./dexieCloudNETBase"; import "./dexieCloudNETCloud"; import "./dexieCloudNETObservables"; -import "../../../DexieNET/yarn/src/dexieNET" export * from "./dexieCloudNETBase"; export * from "./dexieCloudNETCloud"; export * from "./dexieCloudNETObservables"; -export * from "../../../DexieNET/yarn/src/dexieNET"; \ No newline at end of file + +import "./DexieNET/dexieNETBase"; +import "./DexieNET/dexieNETLiveQuery"; +import "./DexieNET/dexieNETTable"; +import "./DexieNET/dexieNETTransactions"; +import "./DexieNET/dexieNETCollection"; +import "./DexieNET/dexieNETPersistence"; + +export * from "./DexieNET/dexieNETBase"; +export * from "./DexieNET/dexieNETLiveQuery"; +export * from "./DexieNET/dexieNETTable"; +export * from "./DexieNET/dexieNETTransactions"; +export * from "./DexieNET/dexieNETCollection"; +export * from "./DexieNET/dexieNETPersistence"; \ No newline at end of file