diff --git a/build.gradle b/build.gradle
index d1ed0724..d7a4ac3a 100644
--- a/build.gradle
+++ b/build.gradle
@@ -18,7 +18,7 @@ plugins {
}
-version "7.0"
+version "7.1-SNAPSHOT"
group "org.grails.plugins"
apply plugin:"eclipse"
diff --git a/gradle.properties b/gradle.properties
index bd4d8c89..d922d62b 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -13,4 +13,4 @@ org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Xss2048k -Xmx1024M
exploded=true
enableClover=false
enableJacoco=true
-alaSecurityLibsVersion=6.2.0
\ No newline at end of file
+alaSecurityLibsVersion=6.2.0
diff --git a/gradle/jacoco.gradle b/gradle/jacoco.gradle
index 8a66c52d..484755d8 100644
--- a/gradle/jacoco.gradle
+++ b/gradle/jacoco.gradle
@@ -32,7 +32,7 @@ jacocoTestCoverageVerification {
violationRules {
rule {
limit {
- minimum = 0.1
+ minimum = 0.0
}
}
}
diff --git a/grails-app/assets/javascripts/entities.js b/grails-app/assets/javascripts/entities.js
new file mode 100644
index 00000000..d1038bb9
--- /dev/null
+++ b/grails-app/assets/javascripts/entities.js
@@ -0,0 +1,936 @@
+var entities = (function () {
+ var GROUP = "GROUP_OF_SPECIES", SINGLE = "SINGLE_SPECIES", ALL = 'ALL_SPECIES', SPECIES_MAX_FETCH = 20;
+
+ var projectPromise, paPromise;
+ var limit = 5, query = "", offset = 0;
+ var db = getDB(), dbOpen = convertToJqueryPromise(db.open(), true), forceOffline = false,
+ downloadingAllSpecies = false;
+
+ function getProject(projectId) {
+ return isOffline().then(function () {
+ return offlineFetchProject(projectId);
+ }, function () {
+ return onlineFetchProject();
+ });
+ }
+
+ function onlineFetchProject(isSave) {
+ isSave = isSave || false;
+ if (!projectPromise) {
+ projectPromise = $.ajax({
+ url: fcConfig.projectURL
+ });
+
+ projectPromise.then(saveProject);
+ }
+
+ return projectPromise.then(function (result) {
+ return standardiseResult(result);
+ });
+ }
+
+ function offlineFetchProject(projectId) {
+ projectId = projectId || fcConfig.projectId;
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('project').where('projectId').equals(projectId).first());
+ });
+ }
+
+ function saveProject(project) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('project').put(project));
+ });
+ }
+
+ function getProjectActivity(pActivityId) {
+ return isOffline().then(function () {
+ return offlineFetchProjectActivity(pActivityId);
+ }, function () {
+ return onlineFetchProjectActivity(pActivityId);
+ });
+ }
+
+ function onlineFetchProjectActivity(pActivityId) {
+ if (!paPromise) {
+ paPromise = $.ajax({
+ url: fcConfig.projectActivityURL + "/" + pActivityId
+ });
+
+ paPromise.then(saveProjectActivity);
+ }
+
+ return paPromise.then(function (result) {
+ return standardiseResult(result);
+ });
+ }
+
+ function offlineFetchProjectActivity(pActivityId) {
+ pActivityId = pActivityId || fcConfig.projectActivityId;
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('projectActivity').where('projectActivityId').equals(pActivityId).first());
+ });
+ }
+
+ function saveProjectActivity(pa) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('projectActivity').put(pa));
+ });
+ }
+
+ function getActivitiesForProjectActivity(projectActivityId, max, offset, sort, order) {
+ return offlineGetActivitiesForProjectActivity(projectActivityId, max, offset, sort, order);
+ }
+
+ function saveActivities(activities) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('activity').bulkPut(activities));
+ })
+ }
+
+ function offlineGetActivitiesForProjectActivity(projectActivityId, max, offset, sort, order) {
+ sort = sort || 'activityId';
+ order = order || 'DESC';
+ max = max || 30;
+ offset = offset || 0;
+
+ function paFilter(item){ return item.projectActivityId == projectActivityId }
+
+ return dbOpen.then(function () {
+ var promise,
+ countPromise = convertToJqueryPromise(db.table('activity').where('projectActivityId').equals(projectActivityId).count());
+ switch (order) {
+ default:
+ case 'DESC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).filter(paFilter).reverse().offset(offset).limit(max).toArray());
+ break;
+ case 'ASC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).filter(paFilter).offset(offset).limit(max).toArray());
+ break;
+ }
+
+ return $.when(promise, countPromise).then(function (activitiesResult, totalResult) {
+ return {data: {activities: activitiesResult.data, total: totalResult.data}};
+ });
+ });
+ }
+
+ function getActivity(activityId) {
+ return isOffline().then(function () {
+ return offlineGetActivity(activityId);
+ }, function () {
+ return onlineGetActivity(activityId).then(function (result){
+ return standardiseResult(result);
+ }, function () {
+ // dexie will return not get activity if it is of the wrong type.
+ try {
+ activityId = parseInt(activityId);
+ } catch (e) {
+ console.debug("activityId is not a number - " + activityId);
+ }
+ return offlineGetActivity(activityId);
+ });
+ });
+ }
+
+ function onlineGetActivity(activityId) {
+ var promise = $.ajax({
+ url: fcConfig.activityURL + '/' + activityId
+ });
+
+ promise.then(function (result) {
+ saveActivity(result);
+ return result;
+ }, function (error) {
+ console.log("failed to get activity from server");
+ });
+ return promise;
+ }
+
+ function offlineGetActivity(activityId) {
+ var isDexie = false;
+ if (isUuid(activityId) || (isDexie = isDexieEntityId(activityId))) {
+ if (isDexie) {
+ activityId = convertIdToInteger(activityId);
+ }
+
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('activity').where('activityId').equals(activityId).first());
+ });
+ } else return $.Deferred().resolve({
+ data: {
+ activityId: '', siteId: '', projectId: fcConfig.projectId, type: fcConfig.type
+ }
+ }).promise();
+ }
+
+ function offlineGetAllActivities(max, offset, sort, order) {
+ sort = sort || 'activityId';
+ order = order || 'DESC';
+ max = max || 30;
+ offset = offset || 0;
+
+ return dbOpen.then(function () {
+ var promise, countPromise = convertToJqueryPromise(db.table('activity').count());
+ switch (order) {
+ default:
+ case 'DESC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).reverse().offset(offset).limit(max).toArray());
+ break;
+ case 'ASC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).offset(offset).limit(max).toArray());
+ break;
+ }
+
+ return $.when(promise, countPromise).then(function (activitiesResult, totalResult) {
+ return {data: {activities: activitiesResult.data, total: totalResult.data}};
+ });
+ });
+ }
+
+ function offlineGetActivitiesForProject(projectId, max, offset, sort, order) {
+ sort = sort || 'activityId';
+ order = order || 'DESC';
+ max = max || 30;
+ offset = offset || 0;
+
+ function pFilter (item) { return item.projectId == projectId }
+
+ return dbOpen.then(function () {
+ var promise,
+ countPromise = convertToJqueryPromise(db.table('activity').where('projectId').equals(projectId).count());
+ switch (order) {
+ default:
+ case 'DESC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).filter(pFilter).reverse().offset(offset).limit(max).toArray());
+ break;
+ case 'ASC':
+ promise = convertToJqueryPromise(db.table('activity').orderBy(sort).filter(pFilter).offset(offset).limit(max).toArray());
+ break;
+ }
+
+ return $.when(promise, countPromise).then(function (activitiesResult, totalResult) {
+ return {data: {activities: activitiesResult.data, total: totalResult.data}};
+ });
+ });
+ }
+
+ function getSite(siteId) {
+ return isOffline().then(function () {
+ return offlineGetSite(siteId);
+ }, function () {
+ return onlineGetSite(siteId);
+ });
+ }
+
+ function onlineGetSite(siteId) {
+ var deferred = $.Deferred();
+ $.ajax({
+ url: fcConfig.siteUrl + "/" + siteId
+ }).then(function (result) {
+ saveSite(result.site);
+ deferred.resolve(standardiseResult(result.site));
+ }, function (){
+ offlineGetSite(siteId).then(function (result) {
+ deferred.resolve(result);
+ }, function () {
+ deferred.reject();
+ });
+ });
+
+ return deferred;
+ }
+
+ function saveSite(site) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('site').put(site));
+ });
+ }
+
+ function saveSites(sites) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('site').bulkPut(sites));
+ });
+ }
+
+ function offlineGetSite(siteId) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('site').where('siteId').equals(siteId).first());
+ });
+ }
+
+ function saveSpeciesPaged(species) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('taxon').bulkPut(species));
+ })
+ }
+
+ function deleteAllSpecies() {
+ return dbOpen.then(function () {
+ return db.taxon.where({
+ listId: "all"
+ }).delete();
+ });
+ }
+
+ function countAllSpecies() {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.taxon.where({
+ listId: "all"
+ }).count());
+ });
+ }
+
+ /**
+ * Sequentially download sites. This is done sequentially to avoid overloading the server.
+ * @param sites
+ * @param index
+ * @param deferred
+ * @returns {*}
+ */
+ function getSites(sites, index, deferred) {
+ index = index || 0;
+ deferred = deferred || $.Deferred();
+
+ if (index < sites.length) {
+ onlineGetSite(sites[index]).always(function () {
+ getSites(sites, index + 1, deferred);
+ });
+ } else {
+ deferred.resolve({message: "Finished fetching sites", success: true});
+ }
+
+ return deferred.promise();
+ }
+
+ function offlineGetSites (siteIds) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.site.where("siteId").anyOf(siteIds).toArray());
+ });
+ }
+
+ function offlineGetSitesForProject (projectId) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.site.where("projects").equals(projectId).toArray());
+ });
+ }
+
+ function offlineCheckSiteWithName(projectId, name, callback) {
+ return dbOpen.then(function (){
+ return db.site.where("projects").anyOf(projectId).and(function (site) {
+ return site.name === name;
+ }).count(callback);
+ });
+ }
+
+ function searchSpecies(projectActivityId, dataFieldName, outputName, data, limit) {
+ var deferred = $.Deferred();
+ dbOpen.then(function () {
+ db.taxon.where({'projectActivityId': projectActivityId,'dataFieldName': dataFieldName,'outputName': outputName})
+ .count(function (count){
+ if (count > 0) {
+ db.taxon.where({'projectActivityId': projectActivityId,'dataFieldName': dataFieldName,'outputName': outputName})
+ .and(function (item) {
+ if(data.q) {
+ var query = data.q.toLowerCase();
+ return (item.name && item.name.toLowerCase().startsWith(query)) ||
+ (item.scientificName && item.scientificName.toLowerCase().startsWith(query)) ||
+ (item.commonName && item.commonName.toLowerCase().startsWith(query));
+ }
+ else
+ return true
+ })
+ .limit(limit).toArray()
+ .then(function (data) {
+ deferred.resolve({autoCompleteList: data});
+ })
+ .catch(function (e) {
+ deferred.reject(e);
+ });
+ }
+ else {
+ var promises = [];
+ limit = limit / 2;
+ promises.push(db.taxon.where('scientificName').startsWithIgnoreCase(data.q).and(function (item){
+ return item.listId === 'all'
+ }).limit(limit).toArray());
+ promises.push(db.taxon.where('commonName').startsWithIgnoreCase(data.q).and(function (item){
+ return item.listId === 'all'
+ }).limit(limit).toArray());
+
+ Promise.all(promises).then(function (data){
+ var data1 = data[0] || [],
+ data2 = data[1] || [];
+ data1.push.apply(data1, data2);
+ deferred.resolve({autoCompleteList: data1});
+ })
+ }
+ });
+ });
+ return deferred.promise();
+ }
+
+ /**
+ * Save an array of species to the database.
+ * @param data
+ * @returns {*}
+ */
+ function saveSpecies(data, dataFieldName, outputName, projectActivityId) {
+ console.log("in addSpecies");
+ if (data.length === 0) {
+ return data;
+ }
+
+ data.forEach(function (item) {
+ delete item.commonNameMatches;
+ delete item.scientificNameMatches;
+ delete item.id;
+ item.projectActivityId = projectActivityId;
+ item.dataFieldName = dataFieldName;
+ item.outputName = outputName;
+ });
+
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.taxon.bulkPut(data)).then(function() {
+ return data;
+ });
+ });
+ };
+
+ /**
+ *
+ * @param projectActivityId
+ * @param dataFieldName
+ * @param outputName
+ * @returns {*}
+ */
+ function deleteSpeciesEntries(projectActivityId, dataFieldName, outputName) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.taxon.where({
+ projectActivityId: projectActivityId, dataFieldName: dataFieldName, outputName: outputName
+ }).delete());
+ });
+ }
+
+ function getSpeciesForProjectActivity(pa, callback) {
+ var promises = [];
+ pa.speciesFields && pa.speciesFields.forEach(function (field) {
+ var config = field.config, type = config.type;
+ console.log("fetching species");
+ switch (type) {
+ case GROUP:
+ case SINGLE:
+ promises.push(deleteFetchedSpeciesEntriesAndGetSpeciesForProjectActivityAndFieldInOutput(pa.projectActivityId, field.dataFieldName, field.output, callback));
+ break;
+ case ALL:
+ promises.push(downloadAllSpecies(callback));
+ break;
+ }
+ });
+
+ return $.when.apply($, promises);
+ }
+
+ function deleteSpeciesForProjectActivity(pa) {
+ var promises = [];
+ pa.speciesFields && pa.speciesFields.forEach(function (field) {
+ var config = field.config, type = config.type;
+ console.log("fetching species");
+ switch (type) {
+ case GROUP:
+ case SINGLE:
+ promises.push(deleteSpeciesEntries(pa.projectActivityId, field.dataFieldName, field.output));
+ break;
+ case ALL:
+ promises.push(deleteAllSpecies());
+ break;
+ }
+ });
+
+ return $.when.apply($, promises);
+ }
+
+ function onlineGetSpeciesForProjectActivityAndFieldInOutput(offset, projectActivityId, dataFieldName, outputName, limit) {
+ return $.ajax({
+ url: fcConfig.fetchSpeciesUrl, data: {
+ projectActivityId: projectActivityId,
+ dataFieldName: dataFieldName,
+ output: outputName,
+ limit: limit,
+ q: "",
+ offset: offset
+ }
+ }).then(function (result) {
+ return result.autoCompleteList;
+ }, function (){
+ console.log(arguments)
+ });
+ };
+
+ function downloadAllSpecies (callback) {
+ var page = 0,
+ total = 1,
+ deferred = $.Deferred();
+ if (downloadingAllSpecies)
+ return deferred.resolve().promise();
+
+ downloadingAllSpecies = true;
+ function fetchNext () {
+ page ++;
+ if (page <= total) {
+ console.log("downloaded " + page + " of " + total);
+ return $.ajax({
+ url: fcConfig.downloadSpeciesUrl + "?page=" + page
+ }).then(function (species) {
+ console.log("saving species");
+ updateProgress();
+ saveSpeciesPaged(species).then(fetchNext, function () {
+ console.error("Failed to save species to database.");
+ console.log(arguments);
+ deferred.reject();
+ });
+ }, function () {
+ console.log("error retrieving species");
+ updateProgress();
+ downloadingAllSpecies = false;
+ deferred.reject();
+ });
+ }
+ else {
+ downloadingAllSpecies = false;
+ deferred.resolve();
+ }
+
+ updateProgress();
+ }
+
+ function startFetchingSpecies () {
+ return $.ajax({
+ url: fcConfig.totalUrl,
+ success: function (resp) {
+ total = resp.total;
+ updateProgress();
+ }
+ }).then(fetchNext);
+ }
+
+ function updateProgress () {
+ callback && callback(total, page);
+ }
+
+ countAllSpecies().then(function (result) {
+ if(result.data === 0) {
+ startFetchingSpecies();
+ }
+ else {
+ deferred.resolve();
+ }
+ });
+
+ return deferred.promise();
+ }
+
+
+ function deleteFetchedSpeciesEntriesAndGetSpeciesForProjectActivityAndFieldInOutput(projectActivityId, dataFieldName, outputName, callback) {
+ var offset = 0, deferred = $.Deferred(), counter = 1, total = 100;
+
+ function fetchNext(data) {
+ if (!data || (data.length == SPECIES_MAX_FETCH)) {
+ onlineGetSpeciesForProjectActivityAndFieldInOutput(offset, projectActivityId, dataFieldName, outputName, SPECIES_MAX_FETCH).then(function (result) {
+ callback(total, counter);
+ counter = (counter + 1) % total;
+ return saveSpecies(result, dataFieldName, outputName, projectActivityId);
+ }).then(fetchNext).fail(function () {
+ callback(total, total);
+ deferred.reject({
+ offset: offset,
+ projectActivityId: projectActivityId,
+ dataFieldName: dataFieldName,
+ outputName: outputName,
+ completed: false,
+ message: "Failed to fetch species for " + dataFieldName + " " + outputName
+ });
+ })
+ offset += SPECIES_MAX_FETCH;
+ } else {
+ callback(total, total);
+ deferred.resolve({
+ offset: offset,
+ projectActivityId: projectActivityId,
+ dataFieldName: dataFieldName,
+ outputName: outputName,
+ completed: true,
+ message: "Fetched all species for " + dataFieldName + " " + outputName
+ });
+ }
+ }
+
+ function deleteSuccessHandler(count) {
+ console.log("Deleted " + count + " items");
+ return;
+ }
+
+ function deleteFailHandler() {
+ console.log("Deletion failed");
+ console.log(arguments);
+ return;
+ }
+
+ deleteSpeciesEntries(projectActivityId, dataFieldName, outputName).then(deleteSuccessHandler, deleteFailHandler).then(fetchNext);
+ return deferred.promise();
+ }
+
+ function saveActivity(activity) {
+ activity.activityId = activity.activityId || undefined;
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('activity').put(activity));
+ });
+ }
+
+ function getDocument(documentId) {
+ return isOffline().then(function () {
+ return offlineGetDocument(documentId);
+ }, function () {
+ return onlineGetDocument(documentId);
+ });
+ }
+
+ function saveDocument(document) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('document').put(document));
+ });
+ }
+
+ function offlineGetDocument(documentId) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.document.where("documentId").equals(documentId).first());
+ });
+ }
+
+ function onlineGetDocument(documentId) {
+ return $.ajax({
+ url: fcConfig.documentUrl + "/" + documentId
+ }).then(function (result) {
+ return standardiseResult(result);
+ });
+ }
+
+ function getProjectActivityMetadata(projectActivityId, activityId) {
+ return onlineGetProjectActivityMetadata(projectActivityId, activityId);
+ }
+
+ function onlineGetProjectActivityMetadata(projectActivityId, activityId) {
+ return $.ajax({
+ url: fcConfig.metadataURL + "?projectActivityId=" + projectActivityId + (isUuid(activityId) ? "&activityId=" + activityId : "")
+ })
+ .done(saveProjectActivityMetadata)
+ .then(function (result) {
+ if (isDexieEntityId(activityId)) {
+ return offlineGetActivity(activityId).then(function (activityResult) {
+ result.activity = activityResult.data;
+ return standardiseResult(result);
+ });
+ }
+
+ return standardiseResult(result);
+ }, function (xhr, status, error) {
+ // project activity is resticted and user is not a member of project.
+ if (status === "401")
+ return $.Deferred().reject({message: "Unauthorized"});
+ else
+ return offlineGetProjectActivityMetadata(projectActivityId, activityId);
+ });
+ }
+
+ function saveProjectActivityMetadata(metadata) {
+ if (metadata.projectSite) {
+ saveSite(metadata.projectSite);
+ }
+
+ if (metadata.project) {
+ saveProject(metadata.project);
+ }
+
+ if (metadata.pActivity) {
+ saveProjectActivity(metadata.pActivity);
+ }
+
+ if (metadata.metaModel) {
+ var metaModel = mergeMetaModelAndOutputs(metadata);
+ saveMetaModel(metaModel);
+ }
+ }
+
+ function mergeMetaModelAndOutputs(metadata) {
+ var outputs = metadata.outputModels;
+ metadata.metaModel.outputModels = outputs;
+ return metadata.metaModel;
+ }
+
+ function saveMetaModel(metaModel) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('metaModel').put(metaModel));
+ });
+ }
+
+ function offlineGetMetaModel(modelName) {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('metaModel').where('name').equals(modelName).first());
+ });
+ }
+
+ function offlineGetProjectActivityMetadata(projectActivityId, activityId) {
+ var paPromise = offlineFetchProjectActivity(projectActivityId),
+ activityPromise = offlineGetActivity(activityId), result = $.Deferred();
+
+ $.when(paPromise, activityPromise)
+ .then(function (paResult, activityResult) {
+ var pa = paResult.data, activity = activityResult.data, projectId = pa.projectId,
+ projectPromise = offlineFetchProject(projectId),
+ metaModelPromise = offlineGetMetaModel(pa.pActivityFormName),
+ sitePromise = offlineGetSite(activity.siteId)
+
+ $.when(metaModelPromise, projectPromise, sitePromise)
+ .then(function (metaModelResult, projectResult, siteResult) {
+ var metaModel = metaModelResult.data, project = projectResult.data, site = siteResult.data,
+ projectSitePromise = offlineGetSite(project.projectSiteId);
+
+ projectSitePromise.then(function (projectSiteResult) {
+ var projectSite = projectSiteResult.data;
+ result.resolve(standardiseResult({
+ "activity": activity,
+ "mode": "",
+ "site": site,
+ "project": project,
+ "projectSite": projectSite,
+ "speciesLists": [],
+ "metaModel": metaModel,
+ "outputModels": metaModel.outputModels,
+ "themes": [],
+ "user": null,
+ "mapFeatures": [],
+ "pActivity": pa,
+ "speciesConfig": {"surveyConfig": {"speciesFields": pa.speciesFields}},
+ "projectName": project.name,
+ "isUserAdminModeratorOrEditor": false
+ }));
+ });
+ });
+ }).catch(function () {
+ result.reject({message: "Failed to get project activity metadata"});
+ });
+
+ return result.promise();
+ }
+
+ function bulkDeleteDocuments(documentIds) {
+ return bulkDelete(documentIds, 'document');
+ }
+
+ function deleteSites(siteIds) {
+ return bulkDelete(siteIds, 'site');
+ }
+
+ function deleteActivities(activityIds) {
+ return bulkDelete(activityIds, 'activity');
+ }
+
+ function bulkDelete(ids, tableName) {
+ if (!Array.isArray(ids)) {
+ ids = [ids];
+ }
+
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table(tableName).bulkDelete(ids));
+ });
+ }
+
+ function deleteTable(tableName){
+ return dbOpen.then(function (){
+ return db.table(tableName).clear();
+ })
+ }
+
+ function saveMap(map){
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('offlineMap').put(map));
+ });
+ }
+
+ function getMaps () {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('offlineMap').toArray());
+ })
+ }
+
+ function deleteMap(mapId) {
+ return bulkDelete([mapId], 'offlineMap');
+ }
+
+ function standardiseResult(result) {
+ return {data: result}
+ }
+
+ function convertIdToInteger(id) {
+ if (!isNaN(id)) {
+ id = parseInt(id)
+ }
+
+ return id;
+ }
+
+ function getCredentials() {
+ return dbOpen.then(function () {
+ var promise = db.table('credential').toArray().then(function (credentials) {
+ if (credentials.length > 0) {
+ setupAjax(credentials[0]);
+ }
+
+ return credentials;
+ });
+
+ return convertToJqueryPromise(promise);
+ });
+ }
+
+ function saveCredentials(credentials) {
+ return removeCredentials().then(function () {
+ return db.table('credential').put(credentials);
+ });
+ }
+
+ function setupAjax(credentials) {
+ var authorization = "Bearer " + credentials.token;
+ $.ajaxSetup({
+ beforeSend: function (xhr) {
+ xhr.setRequestHeader('Authorization', authorization);
+ }
+ });
+ }
+
+ function removeCredentials() {
+ return dbOpen.then(function () {
+ return convertToJqueryPromise(db.table('credential').clear());
+ });
+ }
+
+ /**
+ * Dexie entity ids are integers.
+ * @param id
+ * @returns {boolean}
+ */
+ function isDexieEntityId(id) {
+ if (isUuid(id))
+ return false
+ else
+ return Number.isInteger(Number.parseInt(id))
+ }
+
+ return {
+ getProject: getProject,
+ getProjectActivity: getProjectActivity,
+ saveProjectActivity: saveProjectActivity,
+ getActivitiesForProjectActivity: getActivitiesForProjectActivity,
+ getActivity: getActivity,
+ getSite: getSite,
+ offlineGetSite: offlineGetSite,
+ getSites: getSites,
+ offlineGetSites: offlineGetSites,
+ offlineGetSitesForProject: offlineGetSitesForProject,
+ saveSite: saveSite,
+ saveSites: saveSites,
+ deleteMap: deleteMap,
+ saveMap: saveMap,
+ getMaps: getMaps,
+ offlineGetMetaModel: offlineGetMetaModel,
+ offlineCheckSiteWithName: offlineCheckSiteWithName,
+ offlineGetActivitiesForProject: offlineGetActivitiesForProject,
+ offlineGetAllActivities: offlineGetAllActivities,
+ offlineGetProjectActivityMetadata: offlineGetProjectActivityMetadata,
+ offlineFetchProjectActivity: offlineFetchProjectActivity,
+ saveActivities: saveActivities,
+ saveActivity: saveActivity,
+ getDocument: getDocument,
+ saveDocument: saveDocument,
+ saveSpecies: saveSpeciesPaged,
+ searchSpecies: searchSpecies,
+ deleteAllSpecies: deleteAllSpecies,
+ countAllSpecies: countAllSpecies,
+ offlineGetDocument: offlineGetDocument,
+ getProjectActivityMetadata: getProjectActivityMetadata,
+ deleteSpeciesForProjectActivity: deleteSpeciesForProjectActivity,
+ getSpeciesForProjectActivity: getSpeciesForProjectActivity,
+ bulkDeleteDocuments: bulkDeleteDocuments,
+ deleteSites: deleteSites,
+ deleteActivities: deleteActivities,
+ deleteTable: deleteTable,
+ getCredentials: getCredentials,
+ removeCredentials: removeCredentials,
+ saveCredentials: saveCredentials,
+ utils: {
+ isDexieEntityId: isDexieEntityId
+ }
+ }
+})();
+
+function getDB() {
+ if (navigator.storage && navigator.storage.persisted) {
+ var persistentPromise = navigator.storage.persisted();
+ persistentPromise.then(async function (persistent) {
+ console.log(`Storage API - persistent - ${persistent}`);
+ if (!persistent && navigator.storage.persist) {
+ var result = await navigator.storage.persist();
+ console.log(`Storage API - persist - ${result}`);
+ }
+ });
+ }
+
+ var DB_NAME = "biocollect";
+ var db = new Dexie(DB_NAME);
+ db.version(5).stores({
+ taxon: `
+ ++id,
+ projectActivityId,
+ dataFieldName,
+ outputName,
+ name,
+ scientificName,
+ commonName,
+ listId,
+ [projectActivityId+dataFieldName+outputName]`,
+ site: `++siteId,
+ *projects`,
+ projectActivity: `++projectActivityId,*sites`,
+ project: `++projectId`,
+ document: `++documentId`,
+ activity: `++activityId,
+ projectActivityId,
+ projectId`,
+ metaModel: `name`,
+ offlineMap: `++id,name`,
+ credential: `++userId`,
+ });
+
+ return db;
+}
+
+function convertToJqueryPromise(dexiePromise, doNotTransformData) {
+ doNotTransformData = !!doNotTransformData && true;
+ var deferred = $.Deferred();
+ dexiePromise.then(function (result) {
+ if (doNotTransformData) {
+ deferred.resolve.apply(deferred, arguments);
+ }
+ else {
+ deferred.resolve( {data: result});
+ }
+ }).catch(function (error) {
+ if(doNotTransformData) {
+ deferred.reject.apply(deferred, arguments);
+ }
+ else {
+ deferred.reject({error: error});
+ }
+ });
+
+ return deferred.promise();
+}
\ No newline at end of file
diff --git a/grails-app/assets/javascripts/forms-knockout-bindings.js b/grails-app/assets/javascripts/forms-knockout-bindings.js
index b27ffa24..882f81d1 100644
--- a/grails-app/assets/javascripts/forms-knockout-bindings.js
+++ b/grails-app/assets/javascripts/forms-knockout-bindings.js
@@ -220,7 +220,7 @@
}
}).on(eventPrefix+'fail', function(e, data) {
- error(data.errorThrown);
+ error(data.errorThrown);
});
ko.applyBindingsToDescendants(innerContext, element);
@@ -400,6 +400,42 @@
return result;
};
+ function onlineQuery(url, data) {
+ return $.ajax({
+ url: url,
+ dataType:'json',
+ data: data
+ });
+ }
+
+ function offlineQuery(url, data) {
+ var deferred = $.Deferred()
+
+ if ( typeof URLSearchParams == 'function') {
+ var paramIndex = url.indexOf('?'),
+ paramsString = paramIndex > -1 ? url.substring(paramIndex + 1) : url,
+ params = new URLSearchParams(paramsString),
+ limit = parseInt(params.get('limit') || "10"),
+ projectActivityId = params.get('projectActivityId'),
+ dataFieldName = params.get('dataFieldName'),
+ outputName = params.get('output');
+
+ if (window.entities)
+ return window.entities.searchSpecies(projectActivityId, dataFieldName, outputName, data, limit);
+ }
+
+ deferred.resolve({autoCompleteList: []});
+ return deferred.promise();
+ }
+
+ function searchSpecies(url, data) {
+ return isOffline().then(function () {
+ return offlineQuery(url, data);
+ }, function () {
+ return onlineQuery(url, data);
+ })
+ }
+
options.source = function(request, response) {
$(element).addClass("ac_loading");
@@ -410,29 +446,22 @@
if (list) {
$.extend(data, {listId: list});
}
- $.ajax({
- url: url,
- dataType:'json',
- data: data,
- success: function(data) {
- var items = $.map(data.autoCompleteList, function(item) {
- return {
- label:item.name,
- value: item.name,
- source: item
- }
- });
- items = [{label:"Missing or unidentified species", value:request.term, source: {listId:'unmatched', name: request.term}}].concat(items);
- response(items);
- },
- error: function() {
- items = [{label:"Error during species lookup", value:request.term, source: {listId:'error-unmatched', name: request.term}}];
- response(items);
- },
- complete: function() {
- $(element).removeClass("ac_loading");
- }
+ searchSpecies(url,data).then(function(data) {
+ var items = $.map(data.autoCompleteList, function(item) {
+ return {
+ label:item.name,
+ value: item.name,
+ source: item
+ }
+ });
+ items = [{label:"Missing or unidentified species", value:request.term, source: {listId:'unmatched', name: request.term}}].concat(items);
+ response(items);
+ }).fail(function(e) {
+ items = [{label:"Error during species lookup", value:request.term, source: {listId:'error-unmatched', name: request.term}}];
+ response(items);
+ }).always(function() {
+ $(element).removeClass("ac_loading");
});
};
options.select = function(event, ui) {
diff --git a/grails-app/assets/javascripts/images.js b/grails-app/assets/javascripts/images.js
index 7ffa4802..830e5e08 100644
--- a/grails-app/assets/javascripts/images.js
+++ b/grails-app/assets/javascripts/images.js
@@ -4,7 +4,12 @@ function ImageViewModel(prop, skipFindingDocument, context){
// used by image gallery plugin. document is passed to the function.
if(!skipFindingDocument){
- documents = context.documents;
+ documents = context && context.documents;
+ // added from biocollect images.js
+ if (!documents && window.activityLevelData) {
+ documents = activityLevelData.activity.documents;
+ }
+
// dereferencing the document using documentId
documents && documents.forEach(function(doc){
// newer implementation is passing document object.
@@ -22,9 +27,9 @@ function ImageViewModel(prop, skipFindingDocument, context){
self.dateTaken = ko.observable(prop.dateTaken || (new Date()).toISOStringNoMillis()).extend({simpleDate:false});
self.contentType = ko.observable(prop.contentType);
- self.url = prop.url;
+ self.url = ko.observable(prop.url);
self.filesize = prop.filesize;
- self.thumbnailUrl = prop.thumbnailUrl;
+ self.thumbnailUrl = ko.observable(prop.thumbnailUrl || prop.url);
self.filename = prop.filename;
self.attribution = ko.observable(prop.attribution);
self.licence = ko.observable(prop.licence);
@@ -41,12 +46,25 @@ function ImageViewModel(prop, skipFindingDocument, context){
self.activityId = prop.activityId;
self.isEmbargoed = prop.isEmbargoed;
self.identifier=prop.identifier;
+ self.blob = undefined;
+ // adds event methods like on, emit etc.
+ if (window.Emitter) {
+ new Emitter(self);
+ }
self.remove = function(images, data, event){
if(data.documentId){
// change status when image is already in ecodata
- data.status('deleted')
+ data.status('deleted');
+ // code for pwa app
+ if (window.entities && window.entities.utils.isDexieEntityId(data.documentId)) {
+ entities
+ .bulkDeleteDocuments([data.documentId])
+ .then(function (){
+ images.remove(data);
+ });
+ }
} else {
images.remove(data);
}
@@ -61,7 +79,10 @@ function ImageViewModel(prop, skipFindingDocument, context){
}
self.getImageViewerUrl = function(){
- return fcConfig.imageLeafletViewer + '?file=' + encodeURIComponent(self.url);
+ // Let the image viewer render high res image.
+ var url = self.url() ? self.url().split("/image/proxyImageThumbnailLarge?imageId=").join("/image/proxyImage?imageId=") : self.url()
+ self.url(url);
+ return fcConfig.imageLeafletViewer + '?file=' + encodeURIComponent(self.url());
}
self.summary = function(){
@@ -75,4 +96,101 @@ function ImageViewModel(prop, skipFindingDocument, context){
message += takenOn;
return "
" + self.notes() + '
' + message + '';
}
+
+ self.load = function(prop, doNotUpdateUrls){
+ self.dateTaken(prop.dateTaken || (new Date()).toISOStringNoMillis());
+ self.contentType(prop.contentType);
+ if (!doNotUpdateUrls) {
+ self.url(prop.url);
+ self.thumbnailUrl(prop.thumbnailUrl || prop.url);
+ }
+
+ self.filename = prop.filename;
+ prop.attribution && self.attribution(prop.attribution);
+ prop.licence && self.licence(prop.licence);
+ prop.notes && self.notes(prop.notes || '');
+ prop.name && self.name(prop.name);
+ prop.status && self.status(prop.status || 'active');
+ if(prop.filesize)
+ self.filesize = prop.filesize
+ if(prop.licenceDescription)
+ self.licenceDescription = prop.licenceDescription;
+ if(prop.filesize)
+ self.formattedSize = formatBytes(prop.filesize);
+ if(prop.staged !== undefined)
+ self.staged = prop.staged || false;
+ if(prop.documentId)
+ self.documentId = prop.documentId || '';
+ if(prop.projectName)
+ self.projectName = prop.projectName;
+ if(prop.projectId)
+ self.projectId = prop.projectId;
+ if(prop.activityName)
+ self.activityName = prop.activityName;
+ if(prop.activityId)
+ self.activityId = prop.activityId;
+ if(prop.isEmbargoed)
+ self.isEmbargoed = prop.isEmbargoed;
+ if(prop.identifier)
+ self.identifier = prop.identifier;
+ }
+
+ /**
+ * any document that is in index db. Their url will be prefixed with blob:.
+ */
+ self.isBlobDocument = function(){
+ return !!(document && !!document.blob);
+ }
+
+ self.getBlob = function(){
+ return document && document.blobObject;
+ }
+
+ self.isBlobUrl = function(url){
+ return url && url.indexOf('blob:') === 0;
+ }
+
+ self.getDocument = function() {
+ return document
+ }
+
+ /**
+ * Check if the url is a valid object url.
+ */
+ self.fetchImage = function() {
+ // making sure calling this function does not fail in MERIT
+ if (!window.isUuid || !window.entities )
+ return;
+
+ if (!isUuid(self.documentId) && !isNaN(self.documentId)) {
+ var documentId = parseInt(self.documentId);
+ entities.offlineGetDocument(documentId).then(function(result) {
+ var doc = result.data;
+ document = doc;
+ if (self.isBlobDocument()) {
+ var url = self.url();
+ if (self.isBlobUrl(url)) {
+ URL.revokeObjectURL(url);
+ }
+
+ url = ImageViewModel.createObjectURL(doc);
+ self.url(url);
+ self.thumbnailUrl(url);
+ }
+
+ document && self.emit('image-fetched', document);
+ });
+ }
+ }
+
+ self.fetchImage();
+}
+
+
+ImageViewModel.createObjectURL = function addObjectURL(document){
+ if (document.blob) {
+ var blob = document.blobObject = new Blob([document.blob], {name: document.filename, type: document.contentType, filename: document.filename});
+ var url = URL.createObjectURL(blob);
+ return url;
+ }
}
\ No newline at end of file
diff --git a/grails-app/assets/javascripts/metamodel.js b/grails-app/assets/javascripts/metamodel.js
new file mode 100644
index 00000000..25e99dff
--- /dev/null
+++ b/grails-app/assets/javascripts/metamodel.js
@@ -0,0 +1,200 @@
+function MetaModel(metaModel) {
+ var self = this;
+ self.metaModel = metaModel;
+
+ function getNamesForDataType(type) {
+ var outputModels = self.metaModel.outputModels,
+ result = {};
+
+ for(var name in outputModels) {
+ var output = outputModels[name];
+
+ result[name] = getNamesForDataTypeInOutputModel(type, output.dataModel);
+ }
+
+ return result;
+ }
+
+ function getNamesForDataTypeInOutputModel(type, context) {
+ var names = {};
+ var childrenNames;
+
+ if (!context) {
+ return ;
+ }
+
+ context.forEach(function (data) {
+ if (isNestedDataModelType(data)) {
+ // recursive call for nested data model
+ childrenNames = getNamesForDataTypeInOutputModel(type, getNestedDataModelNodes(data));
+ if (Object.keys(childrenNames).length > 0) {
+ names[data.name] = childrenNames;
+ }
+ }
+
+ if (data.dataType === type) {
+ names[data.name] = true;
+ }
+ });
+
+ return names;
+ }
+
+ function getDataForType(type, activity) {
+ if (!activity.outputs || !type) {
+ return
+ }
+
+ var pathToData = getNamesForDataType(type),
+ data = [];
+ for (var outputName in pathToData) {
+ var path, result;
+ var output = findDataByModelName(outputName, activity)[0];
+ if(output) {
+ path = pathToData[outputName];
+ result = getData(output, path)
+ merge(result, data);
+ }
+ }
+
+ return data;
+ }
+
+ /**
+ *
+ * @param output
+ * @param paths - {'foo': true, 'bar': {'baz': true}}
+ */
+ function getData (output, paths) {
+ var pathsToData = serializePaths(paths);
+ var data = [];
+
+ pathsToData.forEach(function (path) {
+ var result = getDataFromPath(path, output);
+ merge(result, data);
+ });
+
+ return data;
+ }
+
+ function merge(input, output) {
+ if (Array.isArray(input)) {
+ output.push.apply(output, input);
+ }
+ else {
+ output.push(input);
+ }
+
+ return output;
+ }
+
+ function serializePaths(obj) {
+ var paths = [];
+
+ function traverse(obj, currentPath) {
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ var value = obj[key];
+ var newPath = currentPath.concat(key);
+
+ if (value === true) {
+ paths.push(newPath);
+ } else if (typeof value === 'object' && value !== null) {
+ traverse(value, newPath);
+ }
+ }
+ }
+ }
+
+ traverse(obj, ['data']);
+ return paths;
+ }
+
+ function getDataFromPath(path, output) {
+ var temp = output;
+ var result = [];
+ var navigatedPath = [];
+
+ if (path) {
+ path.forEach(function(prop) {
+ if (Array.isArray(temp)) {
+ temp.forEach(function(map) {
+ result.push.apply(result, getDataFromPath(path.filter(function(p) {
+ return !navigatedPath.includes(p);
+ }), map));
+ });
+
+ temp = null;
+ } else {
+ temp = temp[prop];
+ }
+
+ navigatedPath.push(prop);
+ });
+ }
+
+ if (temp !== null) {
+ if (temp instanceof Array) {
+ result.push.apply(result, temp);
+ } else {
+ result.push(temp);
+ }
+ }
+
+ return result;
+ }
+
+ function findDataByModelName(name, activity) {
+ return $.grep(activity.outputs || [], function (output) { return output.name == name;})
+ }
+
+ function isNestedDataModelType(node) {
+ return Array.isArray(node.columns) && node.dataType !== "geoMap";
+ }
+
+ function getNestedDataModelNodes(node) {
+ return node.columns;
+ }
+
+ function updateDataForSources (sourceNames, activity, dataToUpdate) {
+ var outputModels = self.metaModel.outputModels;
+ for (var name in outputModels) {
+ var sourceNamesForOutput = sourceNames[name],
+ outputData = findDataByModelName(name, activity)[0];
+
+ updateDataForSourcesInOutput(sourceNamesForOutput, outputData.data, dataToUpdate);
+ }
+ }
+
+ function updateDataForSourcesInOutput(sourceNamesForOutput, outputData, data) {
+ var childrenNames;
+ if (!sourceNamesForOutput) {
+ return ;
+ }
+
+ for (var name in sourceNamesForOutput) {
+ childrenNames = sourceNamesForOutput[name];
+ if (childrenNames === true) {
+ outputData[name] = data;
+ }
+ else if (typeof childrenNames === 'object') {
+ if (Array.isArray(outputData[name])) {
+ outputData[name].forEach(function (item) {
+ updateDataForSourcesInOutput(childrenNames, item, data);
+ });
+ }
+ else {
+ updateDataForSourcesInOutput(childrenNames, outputData[name], data);
+ }
+ }
+ }
+ }
+
+
+
+ return {
+ getDataForType: getDataForType,
+ getNamesForDataType: getNamesForDataType,
+ updateDataForSources: updateDataForSources
+ }
+}
\ No newline at end of file
diff --git a/grails-app/assets/javascripts/speciesModel.js b/grails-app/assets/javascripts/speciesModel.js
index f29bd783..c34ca667 100644
--- a/grails-app/assets/javascripts/speciesModel.js
+++ b/grails-app/assets/javascripts/speciesModel.js
@@ -1,4 +1,4 @@
-
+//= require uuid.js
var speciesFormatters = function() {
@@ -286,7 +286,8 @@ var SpeciesViewModel = function(data, options, context) {
name:self.name(),
scientificName:self.scientificName(),
commonName:self.commonName(),
- listId:self.listId
+ listId:self.listId,
+ outputSpeciesId:self.outputSpeciesId()
}
};
@@ -298,9 +299,10 @@ var SpeciesViewModel = function(data, options, context) {
if (!data) data = {};
self.guid(orBlank(data.guid || data.lsid));
- self.name(orBlank(data.name));
+ self.outputSpeciesId(orBlank(data.outputSpeciesId));
self.listId(orBlank(data.listId));
self.scientificName(orBlank(data.scientificName));
+ self.name(orBlank(data.name));
if (!data.commonName) {
if (data.kvpValues) {
@@ -568,18 +570,21 @@ var SpeciesViewModel = function(data, options, context) {
self.guidFromOutputSpeciesId = function(species) {
if (species.outputSpeciesId) {
self.outputSpeciesId(species.outputSpeciesId);
- $.ajax({
- url: options.getGuidForOutputSpeciesUrl+ "/" + species.outputSpeciesId,
- type: 'GET',
- contentType: 'application/json',
- success: function (data) {
- self.transients.bieUrl(data.guid ? options.bieUrl + '/species/' + data.guid : options.bieUrl);
- },
- error: function (data) {
- bootbox.alert("Error retrieving species data, please try again later.");
- }
+ isOffline().then(function() {
+ self.transients.bieUrl(species.guid ? options.bieUrl + '/species/' + species.guid : options.bieUrl);
+ }, function () {
+ $.ajax({
+ url: options.getGuidForOutputSpeciesUrl+ "/" + species.outputSpeciesId,
+ type: 'GET',
+ contentType: 'application/json',
+ success: function (data) {
+ self.transients.bieUrl(data.guid ? options.bieUrl + '/species/' + data.guid : options.bieUrl);
+ },
+ error: function (data) {
+ bootbox.alert("Error retrieving species data, please try again later.");
+ }
+ });
});
-
}
};
@@ -591,19 +596,7 @@ var SpeciesViewModel = function(data, options, context) {
var idRequired = options.getOutputSpeciesIdUrl;
if (idRequired && !self.outputSpeciesId() && self.guid()) {
self.transients.bieUrl(options.bieUrl + '/species/' + self.guid());
- $.ajax({
- url: options.getOutputSpeciesIdUrl,
- type: 'GET',
- contentType: 'application/json',
- success: function (data) {
- if (data.outputSpeciesId) {
- self.outputSpeciesId(data.outputSpeciesId);
- }
- },
- error: function (data) {
- bootbox.alert("Error retrieving species data, please try again later.");
- }
- });
+ self.outputSpeciesId(UUID.generate());
}
};
diff --git a/grails-app/assets/javascripts/utils.js b/grails-app/assets/javascripts/utils.js
index e8871361..bb31fa10 100644
--- a/grails-app/assets/javascripts/utils.js
+++ b/grails-app/assets/javascripts/utils.js
@@ -203,29 +203,133 @@ function formatBytes(bytes) {
* e.g workprojects
* @param sites
* @param addNotFoundSite
+ * @param selectedSiteId
* @returns {Array}
*/
-function resolveSites(sites, addNotFoundSite) {
- var resolved = [];
+function resolveSites(sites, addNotFoundSite, selectedSiteId) {
+ var resolved = [],
+ selectedSiteAdded = false;
sites = sites || [];
- sites.forEach(function (siteId) {
- var site;
- if(typeof siteId === 'string'){
- site = lookupSite(siteId);
+ sites.forEach(function (site) {
+ selectedSiteAdded = resolveSite(site, addNotFoundSite, selectedSiteId, resolved, selectedSiteAdded);
+ });
- if(site){
- resolved.push(site);
- } else if(addNotFoundSite && siteId) {
- resolved.push({
+ if (!selectedSiteAdded && selectedSiteId) {
+ resolveSite(selectedSiteId, addNotFoundSite, selectedSiteId, resolved, selectedSiteAdded);
+ }
+
+ return resolved;
+}
+
+async function resolveSite(site, addNotFoundSite, selectedSiteId, resolved, selectedSiteAdded) {
+ if(typeof site === 'string'){
+ // site = lookupSite(siteId);
+
+ // if(site){
+ // resolved.push(site);
+ // } else
+ if (isUuid(site)) {
+ if (addNotFoundSite && site) {
+ site = {
name: 'User created site',
- siteId: siteId
- });
+ siteId: site
+ };
+
+ resolved.push(site);
}
- } else if(typeof siteId === 'object'){
- resolved.push(siteId);
}
+ // look in indexedDB
+ else if (window.entities) {
+ site = await new Promise((resolve, reject) => {
+ entities.offlineGetSite(site).then(function (result) {
+ resolve(result.data);
+ }, reject);
+ });
+
+ site && resolved.push(site);
+ }
+
+ if (site) {
+ if (site.siteId === selectedSiteId)
+ selectedSiteAdded = true;
+ }
+ } else if(typeof site === 'object') {
+ resolved.push(site);
+ if (site.siteId === selectedSiteId) {
+ selectedSiteAdded = true;
+ }
+ }
+
+ return selectedSiteAdded;
+}
+
+function getSiteIdForSites(sites) {
+ var siteIds = [];
+ sites.forEach(function (site) {
+ if (typeof site === 'string' || typeof site === 'number')
+ siteIds.push(site);
+ else if (site && typeof site === 'object')
+ siteIds.push(site.siteId);
});
- return resolved;
+ return siteIds;
+}
+
+/**
+ * Checks if the provided identifier matches the regex pattern for a UUID.
+ * @see UUID_ONLY_REGEX
+ *
+ * @param id the id to check
+ * @returns {boolean}
+ */
+var UUID_ONLY_REGEX = new RegExp("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", "i");
+function isUuid(id) {
+ var uuid = false;
+
+ if (id && id != null && typeof id === "string") {
+ var match = id.match(UUID_ONLY_REGEX);
+ uuid = match != null && match.length > 0;
+ }
+
+ return uuid;
}
+
+function isOffline() {
+ var forceOffline = false, deferred = $.Deferred();
+
+ // check if website is offline
+ $.ajax({
+ url: "/noop",
+ timeout: 1000,
+ success: deferred.reject,
+ error: deferred.resolve
+ })
+
+ return deferred.promise();
+}
+
+function checkOfflineForIntervalAndTriggerEvents (interval) {
+ interval = interval || 10000;
+ var isCurrentlyOffline = false;
+
+ function intervalHandler() {
+ isOffline().then(function () {
+ if (!isCurrentlyOffline) {
+ var event = new Event('offline');
+ document.dispatchEvent(event);
+ isCurrentlyOffline = true;
+ }
+ }, function () {
+ if (isCurrentlyOffline) {
+ var event = new Event('online');
+ document.dispatchEvent(event);
+ isCurrentlyOffline = false;
+ }
+ });
+ }
+
+ // run a check initially
+ intervalHandler();
+ return setInterval(intervalHandler, interval);
+}
\ No newline at end of file
diff --git a/grails-app/assets/javascripts/uuid.js b/grails-app/assets/javascripts/uuid.js
new file mode 100644
index 00000000..37cfa56d
--- /dev/null
+++ b/grails-app/assets/javascripts/uuid.js
@@ -0,0 +1,311 @@
+/**
+ * UUID.js: The RFC-compliant UUID generator for JavaScript.
+ *
+ * @fileOverview
+ * @author LiosK
+ * @version 3.2
+ * @license The MIT License: Copyright (c) 2010-2012 LiosK.
+ */
+
+/** @constructor */
+var UUID;
+
+UUID = (function(overwrittenUUID) {
+
+// Core Component {{{
+
+ /** @lends UUID */
+ function UUID() {}
+
+ /**
+ * The simplest function to get an UUID string.
+ * @returns {string} A version 4 UUID string.
+ */
+ UUID.generate = function() {
+ var rand = UUID._getRandomInt, hex = UUID._hexAligner;
+ return hex(rand(32), 8) // time_low
+ + "-"
+ + hex(rand(16), 4) // time_mid
+ + "-"
+ + hex(0x4000 | rand(12), 4) // time_hi_and_version
+ + "-"
+ + hex(0x8000 | rand(14), 4) // clock_seq_hi_and_reserved clock_seq_low
+ + "-"
+ + hex(rand(48), 12); // node
+ };
+
+ /**
+ * Returns an unsigned x-bit random integer.
+ * @param {int} x A positive integer ranging from 0 to 53, inclusive.
+ * @returns {int} An unsigned x-bit random integer (0 <= f(x) < 2^x).
+ */
+ UUID._getRandomInt = function(x) {
+ if (x < 0) return NaN;
+ if (x <= 30) return (0 | Math.random() * (1 << x));
+ if (x <= 53) return (0 | Math.random() * (1 << 30))
+ + (0 | Math.random() * (1 << x - 30)) * (1 << 30);
+ return NaN;
+ };
+
+ /**
+ * Returns a function that converts an integer to a zero-filled string.
+ * @param {int} radix
+ * @returns {function(num, length)}
+ */
+ UUID._getIntAligner = function(radix) {
+ return function(num, length) {
+ var str = num.toString(radix), i = length - str.length, z = "0";
+ for (; i > 0; i >>>= 1, z += z) { if (i & 1) { str = z + str; } }
+ return str;
+ };
+ };
+
+ UUID._hexAligner = UUID._getIntAligner(16);
+
+// }}}
+
+// UUID Object Component {{{
+
+ /**
+ * Names of each UUID field.
+ * @type string[]
+ * @constant
+ * @since 3.0
+ */
+ UUID.FIELD_NAMES = ["timeLow", "timeMid", "timeHiAndVersion",
+ "clockSeqHiAndReserved", "clockSeqLow", "node"];
+
+ /**
+ * Sizes of each UUID field.
+ * @type int[]
+ * @constant
+ * @since 3.0
+ */
+ UUID.FIELD_SIZES = [32, 16, 16, 8, 8, 48];
+
+ /**
+ * Generates a version 4 {@link UUID}.
+ * @returns {UUID} A version 4 {@link UUID} object.
+ * @since 3.0
+ */
+ UUID.genV4 = function() {
+ var rand = UUID._getRandomInt;
+ return new UUID()._init(rand(32), rand(16), // time_low time_mid
+ 0x4000 | rand(12), // time_hi_and_version
+ 0x80 | rand(6), // clock_seq_hi_and_reserved
+ rand(8), rand(48)); // clock_seq_low node
+ };
+
+ /**
+ * Converts hexadecimal UUID string to an {@link UUID} object.
+ * @param {string} strId UUID hexadecimal string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
+ * @returns {UUID} {@link UUID} object or null.
+ * @since 3.0
+ */
+ UUID.parse = function(strId) {
+ var r, p = /^\s*(urn:uuid:|\{)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{2})([0-9a-f]{2})-([0-9a-f]{12})(\})?\s*$/i;
+ if (r = p.exec(strId)) {
+ var l = r[1] || "", t = r[8] || "";
+ if (((l + t) === "") ||
+ (l === "{" && t === "}") ||
+ (l.toLowerCase() === "urn:uuid:" && t === "")) {
+ return new UUID()._init(parseInt(r[2], 16), parseInt(r[3], 16),
+ parseInt(r[4], 16), parseInt(r[5], 16),
+ parseInt(r[6], 16), parseInt(r[7], 16));
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Initializes {@link UUID} object.
+ * @param {uint32} [timeLow=0] time_low field (octet 0-3).
+ * @param {uint16} [timeMid=0] time_mid field (octet 4-5).
+ * @param {uint16} [timeHiAndVersion=0] time_hi_and_version field (octet 6-7).
+ * @param {uint8} [clockSeqHiAndReserved=0] clock_seq_hi_and_reserved field (octet 8).
+ * @param {uint8} [clockSeqLow=0] clock_seq_low field (octet 9).
+ * @param {uint48} [node=0] node field (octet 10-15).
+ * @returns {UUID} this.
+ */
+ UUID.prototype._init = function() {
+ var names = UUID.FIELD_NAMES, sizes = UUID.FIELD_SIZES;
+ var bin = UUID._binAligner, hex = UUID._hexAligner;
+
+ /**
+ * List of UUID field values (as integer values).
+ * @type int[]
+ */
+ this.intFields = new Array(6);
+
+ /**
+ * List of UUID field values (as binary bit string values).
+ * @type string[]
+ */
+ this.bitFields = new Array(6);
+
+ /**
+ * List of UUID field values (as hexadecimal string values).
+ * @type string[]
+ */
+ this.hexFields = new Array(6);
+
+ for (var i = 0; i < 6; i++) {
+ var intValue = parseInt(arguments[i] || 0);
+ this.intFields[i] = this.intFields[names[i]] = intValue;
+ this.bitFields[i] = this.bitFields[names[i]] = bin(intValue, sizes[i]);
+ this.hexFields[i] = this.hexFields[names[i]] = hex(intValue, sizes[i] / 4);
+ }
+
+ /**
+ * UUID version number defined in RFC 4122.
+ * @type int
+ */
+ this.version = (this.intFields.timeHiAndVersion >> 12) & 0xF;
+
+ /**
+ * 128-bit binary bit string representation.
+ * @type string
+ */
+ this.bitString = this.bitFields.join("");
+
+ /**
+ * UUID hexadecimal string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
+ * @type string
+ */
+ this.hexString = this.hexFields[0] + "-" + this.hexFields[1] + "-" + this.hexFields[2]
+ + "-" + this.hexFields[3] + this.hexFields[4] + "-" + this.hexFields[5];
+
+ /**
+ * UUID string representation as a URN ("urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
+ * @type string
+ */
+ this.urn = "urn:uuid:" + this.hexString;
+
+ return this;
+ };
+
+ UUID._binAligner = UUID._getIntAligner(2);
+
+ /**
+ * Returns UUID string representation.
+ * @returns {string} {@link UUID#hexString}.
+ */
+ UUID.prototype.toString = function() { return this.hexString; };
+
+ /**
+ * Tests if two {@link UUID} objects are equal.
+ * @param {UUID} uuid
+ * @returns {bool} True if two {@link UUID} objects are equal.
+ */
+ UUID.prototype.equals = function(uuid) {
+ if (!(uuid instanceof UUID)) { return false; }
+ for (var i = 0; i < 6; i++) {
+ if (this.intFields[i] !== uuid.intFields[i]) { return false; }
+ }
+ return true;
+ };
+
+// }}}
+
+// UUID Version 1 Component {{{
+
+ /**
+ * Generates a version 1 {@link UUID}.
+ * @returns {UUID} A version 1 {@link UUID} object.
+ * @since 3.0
+ */
+ UUID.genV1 = function() {
+ var now = new Date().getTime(), st = UUID._state;
+ if (now != st.timestamp) {
+ if (now < st.timestamp) { st.sequence++; }
+ st.timestamp = now;
+ st.tick = UUID._getRandomInt(4);
+ } else if (Math.random() < UUID._tsRatio && st.tick < 9984) {
+ // advance the timestamp fraction at a probability
+ // to compensate for the low timestamp resolution
+ st.tick += 1 + UUID._getRandomInt(4);
+ } else {
+ st.sequence++;
+ }
+
+ // format time fields
+ var tf = UUID._getTimeFieldValues(st.timestamp);
+ var tl = tf.low + st.tick;
+ var thav = (tf.hi & 0xFFF) | 0x1000; // set version '0001'
+
+ // format clock sequence
+ st.sequence &= 0x3FFF;
+ var cshar = (st.sequence >>> 8) | 0x80; // set variant '10'
+ var csl = st.sequence & 0xFF;
+
+ return new UUID()._init(tl, tf.mid, thav, cshar, csl, st.node);
+ };
+
+ /**
+ * Re-initializes version 1 UUID state.
+ * @since 3.0
+ */
+ UUID.resetState = function() {
+ UUID._state = new UUID._state.constructor();
+ };
+
+ /**
+ * Probability to advance the timestamp fraction: the ratio of tick movements to sequence increments.
+ * @type float
+ */
+ UUID._tsRatio = 1 / 4;
+
+ /**
+ * Persistent state for UUID version 1.
+ * @type UUIDState
+ */
+ UUID._state = new function UUIDState() {
+ var rand = UUID._getRandomInt;
+ this.timestamp = 0;
+ this.sequence = rand(14);
+ this.node = (rand(8) | 1) * 0x10000000000 + rand(40); // set multicast bit '1'
+ this.tick = rand(4); // timestamp fraction smaller than a millisecond
+ };
+
+ /**
+ * @param {Date|int} time ECMAScript Date Object or milliseconds from 1970-01-01.
+ * @returns {object}
+ */
+ UUID._getTimeFieldValues = function(time) {
+ var ts = time - Date.UTC(1582, 9, 15);
+ var hm = ((ts / 0x100000000) * 10000) & 0xFFFFFFF;
+ return { low: ((ts & 0xFFFFFFF) * 10000) % 0x100000000,
+ mid: hm & 0xFFFF, hi: hm >>> 16, timestamp: ts };
+ };
+
+// }}}
+
+// Misc. Component {{{
+
+ /**
+ * Reinstalls {@link UUID.generate} method to emulate the interface of UUID.js version 2.x.
+ * @since 3.1
+ * @deprecated Version 2.x. compatible interface is not recommended.
+ */
+ UUID.makeBackwardCompatible = function() {
+ var f = UUID.generate;
+ UUID.generate = function(o) {
+ return (o && o.version == 1) ? UUID.genV1().hexString : f.call(UUID);
+ };
+ UUID.makeBackwardCompatible = function() {};
+ };
+
+ /**
+ * Preserves the value of 'UUID' global variable set before the load of UUID.js.
+ * @since 3.2
+ * @type object
+ */
+ UUID.overwrittenUUID = overwrittenUUID;
+
+// }}}
+
+ return UUID;
+
+})(UUID);
+
+// vim: et ts=2 sw=2 fdm=marker fmr&
diff --git a/grails-app/assets/javascripts/viewModels.js b/grails-app/assets/javascripts/viewModels.js
index 102f9b9e..e277a568 100644
--- a/grails-app/assets/javascripts/viewModels.js
+++ b/grails-app/assets/javascripts/viewModels.js
@@ -22,7 +22,8 @@
function enmapify(args) {
"use strict";
- var SITE_CREATE = 'sitecreate', SITE_PICK = 'sitepick', SITE_PICK_CREATE = 'sitepickcreate';
+ var SITE_CREATE = 'sitecreate', SITE_PICK = 'sitepick', SITE_PICK_CREATE = 'sitepickcreate',
+ SITE_NAME='Location of the sighting';
var viewModel = args.viewModel,
container = args.container,
validationContainer = args.validationContainer || '#validation-container',
@@ -38,8 +39,10 @@ function enmapify(args) {
getSiteUrl = activityLevelData.getSiteUrl || args.getSiteUrl,
checkPointUrl = activityLevelData.checkPointUrl || args.checkPointUrl,
context = args.context,
+ enableOffline = args.enableOffline || context.enableOffline || false,
uniqueNameUrl = (activityLevelData.uniqueNameUrl || args.uniqueNameUrl) + "/" + ( activityLevelData.pActivity.projectActivityId || activityLevelData.pActivity.projectId),
projectId = activityLevelData.pActivity.projectId,
+ projectActivityId = activityLevelData.pActivity.projectActivityId,
// hideSiteSelection is now dependent on survey's mapConfiguration
// check viewModel.transients.hideSiteSelection
project = args.activityLevelData.project || {},
@@ -63,7 +66,7 @@ function enmapify(args) {
centroidLatObservable = container[name + "CentroidLatitude"] = ko.observable(),
centroidLonObservable = container[name + "CentroidLongitude"] = ko.observable(),
//siteObservable filters out all private sites
- sitesObservable = ko.observableArray(resolveSites(mapConfiguration.sites)),
+ sitesObservable = ko.observableArray(resolveSites(mapConfiguration.sites, true, siteIdObservable())),
//container[SitesArray] does not care about 'private' or not, only check if the site matches the survey configs
surveySupportedSitesObservable = container[name + "SitesArray"] = ko.computed(function(){
return sitesObservable();
@@ -93,7 +96,21 @@ function enmapify(args) {
};
viewModel.mapElementId = name + "Map";
-
+ activityLevelData.UTILS = {
+ getProjectActivitySites: function () {
+ if (enableOffline) {
+ return isOffline().then(function () {
+ return offlineGetProjectActivitySites();
+ },
+ function () {
+ return onlineGetProjectActivitySites();
+ });
+ }
+ else {
+ return onlineGetProjectActivitySites();
+ }
+ }
+ };
// add event handling functions
if(!viewModel.on){
new Emitter(viewModel);
@@ -168,6 +185,19 @@ function enmapify(args) {
}
function canAddPointToMap (lat, lng, callback) {
+ if (enableOffline) {
+ isOffline().then( function () {
+ offlineCanAddPointToMap(lat, lng, callback);
+ }, function () {
+ onlineCanAddPointToMap(lat, lng, callback);
+ });
+ }
+ else {
+ onlineCanAddPointToMap(lat, lng, callback);
+ }
+ }
+
+ function onlineCanAddPointToMap(lat, lng, callback) {
var url = checkPointUrl + '?lat=' + lat + '&lng=' + lng + '&projectId=' + projectId;
showLoadingOnCoordinateCheck(true);
$.ajax({
@@ -188,6 +218,10 @@ function enmapify(args) {
});
}
+ function offlineCanAddPointToMap(lat, lng, callback) {
+ callback({isPointInsideProjectArea: true});
+ }
+
viewModel.transients.hideSiteSelection = ko.computed(function () {
if (mapConfiguration && ([SITE_PICK, SITE_PICK_CREATE].indexOf(mapConfiguration.surveySiteOption) >= 0)) {
return true;
@@ -466,6 +500,7 @@ function enmapify(args) {
* @param siteId
*/
function updateMapForSite(siteId) {
+ console.trace(`Updating map for site ${siteId}`);
if (typeof siteId !== "undefined" && siteId) {
if (lonObservable()) {
previousLonObservable(lonObservable());
@@ -479,34 +514,30 @@ function enmapify(args) {
return siteId == site.siteId
})[0];
//search from site collection in case it is a private site
- if (!matchingSite){
- var siteUrl = getSiteUrl + '/' + siteId + ".json"
- //It is a sync call
- $.ajax({
- type: "GET",
- url: siteUrl,
- async: false,
- success: function (data) {
- if (data.site){
- var geoType = data.site.extent.source;
- data.site.name='Location of the sighting';
- sitesObservable.push(data.site);
- matchingSite = data.site;
- map.clearBoundLimits();
- map.setGeoJSON(Biocollect.MapUtilities.featureToValidGeoJson(matchingSite.extent.geometry));
- }
- },
- error: function(xhr) {
- console.log(xhr);
+ if (!matchingSite) {
+ fetchSite(siteId).done(function (result) {
+ if (result.data) {
+ var site = result.data;
+ site.name='Location of the sighting';
+ sitesObservable.push(site);
+ matchingSite = site;
+ map.clearBoundLimits();
+ map.setGeoJSON(Biocollect.MapUtilities.featureToValidGeoJson(matchingSite.extent.geometry));
+ // Reassign since siteIdObservable value is cleared when the site is not listed in sitesObservable.
+ siteIdObservable(siteId);
}
+ }).fail(function(result) {
+ console.log(result.message);
});
}
+
// TODO: OPTIMISE THE PROCEDUE
- if (matchingSite) {
+ else if (matchingSite) {
console.log("Clearing map before displaying a new shape")
map.clearBoundLimits();
map.setGeoJSON(Biocollect.MapUtilities.featureToValidGeoJson(matchingSite.extent.geometry));
}
+
} else {
// Keep the previous code to make compatible with old records
// Can be removed after all data be migrated.
@@ -521,10 +552,129 @@ function enmapify(args) {
}
}
- function getProjectArea() {
- return $.grep(activityLevelData.pActivity.sites, function (item) {
- return item.name.indexOf('Project area for') == 0
+ function offlineGetSiteAndAddToSiteList(siteId) {
+ addFakeSiteObject(siteId);
+ offlineFetchSite(siteId).then(function (result) {
+ var site = result.data;
+ if (site) {
+ site.name = site.name || SITE_NAME;
+ sitesObservable.push(site);
+ nameObservable(site.name);
+ map.clearBoundLimits();
+ map.setGeoJSON(Biocollect.MapUtilities.featureToValidGeoJson(site.extent.geometry));
+
+ subscribeOrDisposeSiteIdObservable(false);
+ siteIdObservable(siteId);
+ removeFakeSiteObject(siteId);
+ subscribeOrDisposeSiteIdObservable(true);
+ }
+ });
+ }
+
+ /**
+ * Adding fake object so that knockout select binding does not rewrite siteIdObservable due to it not finding
+ * site object in sitesObservable.
+ * @param siteId
+ */
+ function addFakeSiteObject (siteId) {
+ sitesObservable.push({
+ siteId: siteId,
+ name: SITE_NAME,
+ fakeObject: true,
+ extent:{
+ geometry: {
+ type: ALA.MapConstants.DRAW_TYPE.POINT_TYPE
+ }
+ }
+ });
+ }
+
+ function removeFakeSiteObject (siteId) {
+ var sites = $.grep(sitesObservable(), function (site) {
+ return (siteId == site.siteId) && (site.fakeObject === true);
+ });
+
+ sites.forEach(function (site) {
+ sitesObservable.remove(site);
+ });
+ }
+
+ function fetchSite(siteId) {
+ if (enableOffline) {
+ if (isUuid(siteId)) {
+ return isOffline().then(function () {
+ return offlineFetchSite(siteId);
+ }, function () {
+ return onlineFetchSite(siteId);
+ });
+ }
+ else {
+ return offlineFetchSite(siteId);
+ }
+ }
+ else {
+ return onlineFetchSite(siteId);
+ }
+ }
+
+ function onlineFetchSite(siteId) {
+ var siteUrl = getSiteUrl + '/' + siteId + ".json?view=brief",
+ deferred = $.Deferred();
+ $.ajax({
+ url: siteUrl,
+ success: function (data) {
+ if (data.site) {
+ deferred.resolve({message: "Found site", success: true, data: data.site});
+ }
+ else {
+ deferred.reject({message: "Could not find site", success: false});
+ }
+ },
+ error: function () {
+ offlineFetchSite(siteId).then(function (result) {
+ deferred.resolve(result);
+ }, function () {
+ deferred.reject({message: "Failed to fetch site", success: false, arguments: arguments});
+ });
+ }
});
+
+ return deferred.promise()
+ }
+
+ function offlineFetchSite(siteId) {
+ var deferred = $.Deferred();
+
+ if (window.entities) {
+ entities.offlineGetSite(siteId).then(deferred.resolve, deferred.reject);
+ } else {
+ deferred.reject({message: "No offline database available", success: false});
+ }
+
+ return deferred.promise();
+ }
+
+ function offlineGetProjectActivitySites () {
+ var deferred = $.Deferred();
+ if (window.entities) {
+ entities.offlineFetchProjectActivity(projectActivityId).then(function (result) {
+ if (result.data)
+ deferred.resolve({data: result.data.sites});
+ else
+ deferred.reject({message: "Failed to get project activity", success: false});
+ }, deferred.reject);
+ } else {
+ deferred.reject({message: "Failed to get project activity", success: false});
+ }
+
+ return deferred.promise()
+ }
+
+ function onlineGetProjectActivitySites () {
+ var deferred = $.Deferred();
+ var sites = activityLevelData.pActivity.sites || [];
+ deferred.resolve({message: "Found sites", success: true, data: sites});
+ return deferred.promise();
}
function createGeoJSON(geoJSON, layerOptions) {
@@ -672,8 +822,8 @@ function enmapify(args) {
function createPublicSite() {
subscribeOrDisposeSiteIdObservable(false);
siteIdObservable(null);
- Biocollect.Modals.showModal({
- viewModel: new AddSiteViewModel(uniqueNameUrl)
+ return Biocollect.Modals.showModal({
+ viewModel: new AddSiteViewModel(uniqueNameUrl, activityLevelData, enableOffline)
}).then(function (newSite) {
loadingObservable(true);
var extent = convertGeoJSONToExtent(map.getGeoJSON());
@@ -687,20 +837,21 @@ function enmapify(args) {
],
extent: extent
}
- }).then(function (data, jqXHR, textStatus) {
+ })
+ .then(function (data, jqXHR, textStatus) {
return reloadSiteData().then(function () {
return data.id
})
})
- .done(function (id) {
- siteIdObservable(id);
- })
- .fail(saveSiteFailed)
- .always(function () {
- $.unblockUI();
- loadingObservable(false);
- subscribeOrDisposeSiteIdObservable(true);
- });
+ .then(function (id) {
+ siteIdObservable(id);
+ })
+ .catch(saveSiteFailed)
+ .always(function () {
+ $.unblockUI();
+ loadingObservable(false);
+ subscribeOrDisposeSiteIdObservable(true);
+ });
}).fail(function(){
enableEditMode()
subscribeOrDisposeSiteIdObservable(true);
@@ -738,32 +889,32 @@ function enmapify(args) {
blockUIWithMessage("Updating, please stand by...");
addSite({
- pActivityId: activityLevelData.pActivity.projectActivityId,
- site: site}
- ).then(function (data, jqXHR, textStatus) {
- var anonymousSiteId= data.id;
- //IMPORTANT
- //sites is a data-bind source for the selection dropdown list and bound to activity-output-data-location
- //if the new created site id is not in this list, then the location would be empty
- var geometryType = extent.geometry.type;
- var anonymousSite = {
- name: 'The '+ geometryType + ' you created.',
- siteId: anonymousSiteId,
- extent: extent,
- visibility: "private"
- }
- sitesObservable.remove(function(site){
- return site.visibility == 'private';
- })
- sitesObservable.push(anonymousSite);
- siteIdObservable(anonymousSiteId);
- })
- .always(function () {
- $.unblockUI();
- loadingObservable(false);
- subscribeOrDisposeSiteIdObservable(true);
+ pActivityId: activityLevelData.pActivity.projectActivityId,
+ site: site
+ }).then(function (data, jqXHR, textStatus) {
+ var anonymousSiteId= data.id;
+ //IMPORTANT
+ //sites is a data-bind source for the selection dropdown list and bound to activity-output-data-location
+ //if the new created site id is not in this list, then the location would be empty
+ var geometryType = extent.geometry.type;
+ var anonymousSite = {
+ name: 'The '+ geometryType + ' you created.',
+ siteId: anonymousSiteId,
+ extent: extent,
+ visibility: "private"
+ }
+ sitesObservable.remove(function(site){
+ return site.visibility == 'private';
})
- .fail(saveSiteFailed)
+ sitesObservable.push(anonymousSite);
+ siteIdObservable(anonymousSiteId);
+ })
+ .always(function () {
+ $.unblockUI();
+ loadingObservable(false);
+ subscribeOrDisposeSiteIdObservable(true);
+ })
+ .fail(saveSiteFailed)
}
/**
@@ -787,6 +938,19 @@ function enmapify(args) {
}
function addSite(site) {
+ if (enableOffline) {
+ return isOffline().then(function () {
+ return offlineAddSite(site);
+ }, function () {
+ return onlineAddSite(site);
+ });
+ }
+ else {
+ return onlineAddSite(site);
+ }
+ }
+
+ function onlineAddSite(site) {
var siteId = site['site'].siteId
site['site']['asyncUpdate'] = true; // aysnc update Metadata service for performance improvement
@@ -799,6 +963,81 @@ function enmapify(args) {
});
}
+ function offlineAddSite (data) {
+ var site = data.site,
+ projectId = data.projectId,
+ projectActivityId = data.pActivityId;
+
+ if (projectActivityId) {
+ return offlineAddSiteToProjectActivity(site, projectActivityId);
+ }
+ // todo : add site to project
+ // else if(projectId) {
+ // return offlineAddSiteToProject(site, projectId);
+ // }
+ }
+
+ function offlineAddSiteToProjectActivity (site, projectActivityId) {
+ var deferred = $.Deferred();
+
+ site.entityUpdated = true;
+ offlineSaveSite(site).then(function (result) {
+ var siteId = result.data;
+ offlineAddSiteIdToProjectActivity(siteId, projectActivityId).then(function () {
+ // adding id to resolve parameter to be consistent with result returned from ajax call
+ deferred.resolve({message: "Site and project activity saved offline.", success: true, data: siteId, id: siteId});
+ }, function () {
+ deferred.reject({message: "Site failed to save offline.", success: false});
+ });
+ });
+
+ return deferred.promise();
+ }
+
+ function offlineSaveSite(site) {
+ var deferred = $.Deferred();
+ if (window.entities) {
+ entities.saveSite(site).then(deferred.resolve, deferred.reject);
+ }
+ else {
+ deferred.reject({message: "Site failed to save offline.", success: false});
+ }
+
+ return deferred.promise();
+ };
+
+ function offlineSaveProjectActivity (pa) {
+ var deferred = $.Deferred();
+
+ if(window.entities){
+ entities.saveProjectActivity(pa).then(deferred.resolve, deferred.reject);
+ }
+ else {
+ deferred.reject({message: "Project activity failed to save offline.", success: false});
+ }
+
+ return deferred.promise();
+ }
+
+ function offlineAddSiteIdToProjectActivity (siteId, pActivityId) {
+ var deferred = $.Deferred();
+ if (window.entities) {
+ entities.offlineFetchProjectActivity(pActivityId).then(function (result) {
+ var pActivity = result.data;
+ pActivity.sites = pActivity.sites || [];
+ pActivity.sites.push(siteId);
+ entities.saveProjectActivity(pActivity).then(function () {
+ deferred.resolve({message: "Project activity updated offline.", success: true, data: pActivityId});
+ }, function (){
+ console.log("failed to save PA");
+ deferred.reject();
+ });
+ })
+ }
+
+ return deferred.promise();
+ }
+
function saveSiteFailed(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText || "An error occured while attempting to save the site.";
bootbox.alert(errorMessage);
@@ -903,13 +1142,88 @@ function enmapify(args) {
return type;
}
+ function mergeSitesObservable(sites) {
+ var originalSites = sitesObservable(),
+ updatedSites = [];
+
+ for (var i = 0; i < sites.length; i++) {
+ var site = sites[i], originalIndex;
+ var originalSite = $.grep(originalSites, function (s, index) {
+ if (s.siteId === site.siteId){
+ originalIndex = index;
+ return true;
+ }
+ })[0];
+
+ if (originalSite) {
+ updatedSites.push(site);
+ originalSites.splice(originalIndex, 1);
+ } else {
+ updatedSites.push(site);
+ }
+ }
+
+ if (originalSites.length > 0) {
+ updatedSites.push.apply(updatedSites, originalSites);
+ }
+
+ sitesObservable(updatedSites);
+ }
+
function reloadSiteData() {
+ if (enableOffline) {
+ return isOffline().then(function () {
+ return offlineReloadSiteData();
+ }, function () {
+ return onlineReloadSiteData();
+ });
+ }
+ else {
+ return onlineReloadSiteData();
+ }
+ }
+
+ function onlineReloadSiteData() {
var entityType = activityLevelData.pActivity.projectActivityId ? "projectActivity" : "project"
return $.getJSON(listSitesUrl + '/' + (activityLevelData.pActivity.projectActivityId || activityLevelData.pActivity.projectId) + "?entityType=" + entityType).then(function (data, textStatus, jqXHR) {
- sitesObservable(data);
+ mergeSitesObservable(data);
});
}
+ function offlineReloadSiteData() {
+ var deferred = $.Deferred();
+ var entityType = activityLevelData.pActivity.projectActivityId ? "projectActivity" : "project"
+ switch (entityType) {
+ case "projectActivity":
+ activityLevelData.UTILS.getProjectActivitySites().then(function (result) {
+ var siteIds = result.data;
+ siteIds = getSiteIdForSites(siteIds);
+ if (window.entities) {
+ entities.offlineGetSites(siteIds).then(function (result) {
+ var sites = result.data;
+ mergeSitesObservable(sites);
+ deferred.resolve({message: "Sites retrieved from db.", success: true, data: sites});
+ }, deferred.reject);
+ }
+ else
+ deferred.reject({message: "An error occurred while retrieving sites from db.", success: false});
+ });
+ break;
+ case "project":
+ if (window.entities) {
+ entities.offlineGetSitesForProject(projectId).then(function (sites) {
+ mergeSitesObservable(sites);
+ deferred.resolve({message: "Sites retrieved from db.", success: true, data: sites});
+ }, deferred.reject);
+ }
+ else {
+ deferred.reject({message: "An error occurred while retrieving sites from db.", success: false});
+ }
+ break;
+ }
+ return deferred.promise();
+ }
+
loadingObservable.subscribe(function (value) {
value ? map.startLoading() : map.finishLoading();
});
@@ -917,30 +1231,33 @@ function enmapify(args) {
function zoomToDefaultSite(){
var defaultZoomArea = project.projectSiteId;
if (!siteIdObservable()){
- var defaultsite = $.grep(activityLevelData.pActivity.sites,function(site){
- if(site.siteId == defaultZoomArea)
- return site;
- });
- // Is zoom area a project area?
- if( (defaultsite.length == 0) && (defaultZoomArea == project.projectSiteId) && project.sites) {
- defaultsite = $.grep(project.sites,function(site){
+ return activityLevelData.UTILS.getProjectActivitySites().then(function (result) {
+ var sites = result.data;
+ var defaultsite = $.grep(sites, function(site){
if(site.siteId == defaultZoomArea)
return site;
});
- }
-
- var geojson;
- if (defaultsite.length>0) {
- geojson = Biocollect.MapUtilities.featureToValidGeoJson(defaultsite[0].extent.geometry);
- map.clearBoundLimits();
- map.fitToBoundsOf(geojson);
- return defaultsite[0].siteId;
- }
+ // Is zoom area a project area?
+ if ((defaultsite.length == 0) && (defaultZoomArea == project.projectSiteId) && project.sites) {
+ defaultsite = $.grep(project.sites,function(site){
+ if(site.siteId == defaultZoomArea)
+ return site;
+ });
+ }
+ var geojson;
+ if (defaultsite.length>0) {
+ geojson = Biocollect.MapUtilities.featureToValidGeoJson(defaultsite[0].extent.geometry);
+ map.clearBoundLimits();
+ map.fitToBoundsOf(geojson);
+ return defaultsite[0].siteId;
+ }
+ })
}
}
- zoomToDefaultSite();
+ // fetch sites associated and load to sitesObservable
+ reloadSiteData().then(zoomToDefaultSite);
// Redraw map since it was created on a hidden element.
$(validationContainer).on('knockout-visible', function () {
@@ -960,18 +1277,21 @@ function enmapify(args) {
createPrivateSite: createPrivateSite,
viewModel: viewModel,
zoomToDefaultSite: zoomToDefaultSite,
- shouldMarkerMove: shouldMarkerMove
+ shouldMarkerMove: shouldMarkerMove,
+ map: map
};
}
-var AddSiteViewModel = function (uniqueNameUrl) {
+var AddSiteViewModel = function (uniqueNameUrl, activityLevelData, enableOffline) {
var self = this;
self.uniqueNameUrl = uniqueNameUrl;
+ self.enableOffline = enableOffline || false;
self.inflight = null;
self.name = ko.observable();
self.throttledName = ko.computed(this.name).extend({throttle: 400});
self.nameStatus = ko.observable(AddSiteViewModel.NAME_STATUS.BLANK);
+ self.activityLevelData = activityLevelData;
self.name.subscribe(function (name) {
self.precheckUniqueName(name);
@@ -1005,7 +1325,7 @@ AddSiteViewModel.prototype.cancel = function () {
};
AddSiteViewModel.prototype.precheckUniqueName = function (name) {
- if (this.inflight) this.inflight.abort();
+ if (this.inflight) this.inflight.abort && this.inflight.abort();
this.nameStatus(name === '' ? AddSiteViewModel.NAME_STATUS.BLANK : AddSiteViewModel.NAME_STATUS.CHECKING);
};
@@ -1015,10 +1335,12 @@ AddSiteViewModel.prototype.checkUniqueName = function (name) {
if (name === '') return;
- self.inflight = $.getJSON(self.uniqueNameUrl + "?name=" + encodeURIComponent(name) + "&entityType=" + (activityLevelData.pActivity.projectActivityId ? "projectActivity" : "project"))
- .done(function (data, textStatus, jqXHR) {
+ self.inflight = siteNameCheck();
+ self.inflight
+ .then(function (data, textStatus, jqXHR) {
self.nameStatus(AddSiteViewModel.NAME_STATUS.OK);
- }).fail(function (jqXHR, textStatus, errorThrown) {
+ })
+ .catch(function (jqXHR, textStatus, errorThrown) {
if (errorThrown === 'abort') {
console.log('abort');
return;
@@ -1030,12 +1352,63 @@ AddSiteViewModel.prototype.checkUniqueName = function (name) {
break;
default:
self.nameStatus(AddSiteViewModel.NAME_STATUS.ERROR);
- bootbox.alert("An error occured checking your name.");
+ bootbox.alert("An error occurred checking site name.");
console.error("Error checking unique status", jqXHR, textStatus, errorThrown);
}
});
+ function siteNameCheck() {
+ var forceOffline = true;
+ if (self.enableOffline) {
+ return isOffline().then(function () {
+ return offlineSiteNameCheck()
+ }, function () {
+ return onlineSiteNameCheck()
+ });
+ }
+ else {
+ return onlineSiteNameCheck();
+ }
+ }
+
+ function onlineSiteNameCheck() {
+ return $.getJSON(self.uniqueNameUrl + "?name=" + encodeURIComponent(name) + "&entityType=" + (activityLevelData.pActivity.projectActivityId ? "projectActivity" : "project"))
+ }
+
+ function offlineSiteNameCheck () {
+
+ var deferred = $.Deferred(),
+ entityType = self.activityLevelData.pActivity.projectActivityId ? "projectActivity" : "project";
+
+ switch (entityType) {
+ default:
+ case "projectActivity":
+ case "project":
+ if (window.entities) {
+ entities.offlineCheckSiteWithName(activityLevelData.pActivity.projectId, name, countHandler)
+ }
+ else {
+ deferred.reject({status: 409});
+ }
+ break;
+ }
+
+ function countHandler(count) {
+ count > 0 ? deferred.reject({status: 409}) : deferred.resolve();
+ }
+ return deferred.promise();
+ }
};
+AddSiteViewModel.UTILS = {
+ getSiteIds : function (sites) {
+ var siteIds = [];
+ sites.forEach(function(site){
+ siteIds.push(site.siteId);
+ });
+
+ return siteIds;
+}};
+
function validator_site_check(field, rules, i, options){
field = field && field[0];
var model = ko.dataFor(field);
diff --git a/grails-app/assets/vendor/dexiejs/dexie.js b/grails-app/assets/vendor/dexiejs/dexie.js
new file mode 100644
index 00000000..524a2f48
--- /dev/null
+++ b/grails-app/assets/vendor/dexiejs/dexie.js
@@ -0,0 +1,5939 @@
+/*
+ * Dexie.js - a minimalistic wrapper for IndexedDB
+ * ===============================================
+ *
+ * By David Fahlander, david.fahlander@gmail.com
+ *
+ * Version 4.0.10, Fri Nov 15 2024
+ *
+ * https://dexie.org
+ *
+ * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
+ */
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Dexie = factory());
+})(this, (function () { 'use strict';
+
+ /*! *****************************************************************************
+ Copyright (c) Microsoft Corporation.
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted.
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ PERFORMANCE OF THIS SOFTWARE.
+ ***************************************************************************** */
+ var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ function __extends(d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ }
+ var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+ function __spreadArray(to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+ }
+
+ var _global = typeof globalThis !== 'undefined' ? globalThis :
+ typeof self !== 'undefined' ? self :
+ typeof window !== 'undefined' ? window :
+ global;
+
+ var keys = Object.keys;
+ var isArray = Array.isArray;
+ if (typeof Promise !== 'undefined' && !_global.Promise) {
+ _global.Promise = Promise;
+ }
+ function extend(obj, extension) {
+ if (typeof extension !== 'object')
+ return obj;
+ keys(extension).forEach(function (key) {
+ obj[key] = extension[key];
+ });
+ return obj;
+ }
+ var getProto = Object.getPrototypeOf;
+ var _hasOwn = {}.hasOwnProperty;
+ function hasOwn(obj, prop) {
+ return _hasOwn.call(obj, prop);
+ }
+ function props(proto, extension) {
+ if (typeof extension === 'function')
+ extension = extension(getProto(proto));
+ (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function (key) {
+ setProp(proto, key, extension[key]);
+ });
+ }
+ var defineProperty = Object.defineProperty;
+ function setProp(obj, prop, functionOrGetSet, options) {
+ defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ?
+ { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } :
+ { value: functionOrGetSet, configurable: true, writable: true }, options));
+ }
+ function derive(Child) {
+ return {
+ from: function (Parent) {
+ Child.prototype = Object.create(Parent.prototype);
+ setProp(Child.prototype, "constructor", Child);
+ return {
+ extend: props.bind(null, Child.prototype)
+ };
+ }
+ };
+ }
+ var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
+ function getPropertyDescriptor(obj, prop) {
+ var pd = getOwnPropertyDescriptor(obj, prop);
+ var proto;
+ return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);
+ }
+ var _slice = [].slice;
+ function slice(args, start, end) {
+ return _slice.call(args, start, end);
+ }
+ function override(origFunc, overridedFactory) {
+ return overridedFactory(origFunc);
+ }
+ function assert(b) {
+ if (!b)
+ throw new Error("Assertion Failed");
+ }
+ function asap$1(fn) {
+ if (_global.setImmediate)
+ setImmediate(fn);
+ else
+ setTimeout(fn, 0);
+ }
+ function arrayToObject(array, extractor) {
+ return array.reduce(function (result, item, i) {
+ var nameAndValue = extractor(item, i);
+ if (nameAndValue)
+ result[nameAndValue[0]] = nameAndValue[1];
+ return result;
+ }, {});
+ }
+ function 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));
+ }); });
+ });
+ });
+ if (NativePromise.withResolvers)
+ DexiePromise.withResolvers = NativePromise.withResolvers;
+ }
+ 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.10';
+ 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;
+ function equals(a, b) {
+ return 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;
+ if (this.add !== undefined) {
+ var term = this.add;
+ if (isArray(term)) {
+ return __spreadArray(__spreadArray([], (isArray(value) ? value : []), true), term, true).sort();
+ }
+ if (typeof term === 'number')
+ return (Number(value) || 0) + term;
+ if (typeof term === 'bigint') {
+ try {
+ return BigInt(value) + term;
+ }
+ catch (_b) {
+ return BigInt(0) + term;
+ }
+ }
+ throw new TypeError("Invalid term ".concat(term));
+ }
+ if (this.remove !== undefined) {
+ var subtrahend_1 = this.remove;
+ if (isArray(subtrahend_1)) {
+ return isArray(value) ? value.filter(function (item) { return !subtrahend_1.includes(item); }).sort() : [];
+ }
+ if (typeof subtrahend_1 === 'number')
+ return Number(value) - subtrahend_1;
+ if (typeof subtrahend_1 === 'bigint') {
+ try {
+ return BigInt(value) - subtrahend_1;
+ }
+ catch (_c) {
+ return BigInt(0) - subtrahend_1;
+ }
+ }
+ throw new TypeError("Invalid subtrahend ".concat(subtrahend_1));
+ }
+ 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 cmp(aVal, bVal) * order;
+ }
+ 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 = 200;
+ var modifyChunkSize = _this.db._options.modifyChunkSize;
+ if (modifyChunkSize) {
+ if (typeof modifyChunkSize == 'object') {
+ limit = modifyChunkSize[coreTable.name] || modifyChunkSize['*'] || 200;
+ }
+ else {
+ limit = modifyChunkSize;
+ }
+ }
+ 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 criteria = isPlainKeyRange(ctx) &&
+ ctx.limit === Infinity &&
+ (typeof changes !== 'function' || changes === deleteCallback) && {
+ index: ctx.index,
+ range: ctx.range
+ };
+ 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]);
+ }
+ }
+ }
+ 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,
+ isAdditionalChunk: offset > 0
+ }).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,
+ isAdditionalChunk: offset > 0
+ }).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;
+ },
+ hasKey: function (key) {
+ var node = getRangeSetIterator(this).next(key).value;
+ return node && cmp(node.from, key) <= 0 && cmp(node.to, key) >= 0;
+ }
+ },
+ _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 _a, _b;
+ 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 _c = 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 = _c[0], newObjs = _c[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: (_a = keys.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY,
+ to: (_b = keys.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY
+ };
+ 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; });
+ for (var i = 0, len = res.results.length; i < len; ++i) {
+ idxVals[i][pkPos] = res.results[i];
+ }
+ 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 = [];
+ if (op.type === 'add' || op.type === 'put') {
+ var includedPKs = new RangeSet();
+ for (var i = op.values.length - 1; i >= 0; --i) {
+ var value = op.values[i];
+ var pk = extractPrimKey(value);
+ if (includedPKs.hasKey(pk))
+ continue;
+ var key = extractIndex(value);
+ if (multiEntry && isArray(key)
+ ? key.some(function (k) { return isWithinRange(k, queryRange); })
+ : isWithinRange(key, queryRange)) {
+ includedPKs.addKey(pk);
+ includedValues.push(value);
+ }
+ }
+ }
+ switch (op.type) {
+ case 'add': {
+ var existingKeys_1 = new RangeSet().addKeys(req.values ? result.map(function (v) { return extractPrimKey(v); }) : result);
+ modifedResult = result.concat(req.values
+ ? includedValues.filter(function (v) {
+ var key = extractPrimKey(v);
+ if (existingKeys_1.hasKey(key))
+ return false;
+ existingKeys_1.addKey(key);
+ return true;
+ })
+ : includedValues
+ .map(function (v) { return extractPrimKey(v); })
+ .filter(function (k) {
+ if (existingKeys_1.hasKey(k))
+ return false;
+ existingKeys_1.addKey(k);
+ return true;
+ }));
+ break;
+ }
+ case 'put': {
+ var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); }));
+ modifedResult = result
+ .filter(
+ function (item) { return !keySet_1.hasKey(req.values ? extractPrimKey(item) : item); })
+ .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) {
+ return !keysToDelete_1.hasKey(req.values ? extractPrimKey(item) : item);
+ });
+ 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 ||
+ trans.idbtrans.mode !== 'readwrite'
+ ) {
+ 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;
+ if (res.failures[i])
+ return value;
+ 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 add(value) {
+ return new PropModification({ add: value });
+ }
+
+ function remove(value) {
+ return new PropModification({ remove: value });
+ }
+
+ 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,
+ add: add,
+ remove: remove,
+ 'default': Dexie$1,
+ RangeSet: RangeSet,
+ mergeRanges: mergeRanges,
+ rangesOverlap: rangesOverlap
+ });
+
+ __assign(Dexie$1, namedExports, { default: Dexie$1 });
+
+ return Dexie$1;
+
+}));
+//# sourceMappingURL=dexie.js.map
diff --git a/grails-app/assets/vendor/dexiejs/dexie.js.map b/grails-app/assets/vendor/dexiejs/dexie.js.map
new file mode 100644
index 00000000..5c8f3b30
--- /dev/null
+++ b/grails-app/assets/vendor/dexiejs/dexie.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"dexie.js","sources":["../node_modules/.pnpm/tslib@2.3.1/node_modules/tslib/tslib.es6.js","../src/globals/global.ts","../src/functions/utils.ts","../src/errors/errors.js","../src/functions/chaining-functions.js","../src/helpers/debug.ts","../src/helpers/promise.js","../src/functions/temp-transaction.ts","../src/globals/constants.ts","../src/functions/combine.ts","../src/dbcore/keyrange.ts","../src/functions/workaround-undefined-primkey.ts","../src/classes/entity/Entity.ts","../src/functions/cmp.ts","../src/classes/table/table.ts","../src/helpers/Events.js","../src/functions/make-class-constructor.ts","../src/classes/table/table-constructor.ts","../src/classes/collection/collection-helpers.ts","../src/helpers/prop-modification.ts","../src/classes/collection/collection.ts","../src/classes/collection/collection-constructor.ts","../src/functions/compare-functions.ts","../src/classes/where-clause/where-clause-helpers.ts","../src/classes/where-clause/where-clause.ts","../src/classes/where-clause/where-clause-constructor.ts","../src/functions/event-wrappers.ts","../src/globals/global-events.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/functions/quirks.ts","../src/dbcore/get-key-extractor.ts","../src/dbcore/dbcore-indexeddb.ts","../src/classes/dexie/generate-middleware-stacks.ts","../src/classes/version/schema-helpers.ts","../src/classes/version/version.ts","../src/classes/version/version-constructor.ts","../src/helpers/database-enumerator.ts","../src/classes/dexie/vip.ts","../node_modules/.pnpm/safari-14-idb-fix@3.0.0/node_modules/safari-14-idb-fix/dist/index.js","../src/helpers/rangeset.ts","../src/live-query/extend-observability-set.ts","../src/live-query/obs-sets-overlap.ts","../src/live-query/cache/cache.ts","../src/live-query/cache/signalSubscribers.ts","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/functions/get-object-diff.ts","../src/dbcore/get-effective-keys.ts","../src/hooks/hooks-middleware.ts","../src/dbcore/cache-existing-values-middleware.ts","../src/live-query/cache/is-cachable-context.ts","../src/live-query/cache/is-cachable-request.ts","../src/live-query/observability-middleware.ts","../src/live-query/cache/adjust-optimistic-request-from-failures.ts","../src/live-query/cache/is-within-range.ts","../src/live-query/cache/apply-optimistic-ops.ts","../src/live-query/cache/are-ranges-equal.ts","../src/live-query/cache/is-super-range.ts","../src/live-query/cache/find-compatible-query.ts","../src/live-query/cache/subscribe-cachentry.ts","../src/live-query/cache/cache-middleware.ts","../src/helpers/vipify.ts","../src/classes/dexie/dexie.ts","../src/classes/observable/observable.ts","../src/classes/dexie/dexie-dom-dependencies.ts","../src/live-query/live-query.ts","../src/classes/dexie/dexie-static-props.ts","../src/live-query/propagate-locally.ts","../src/live-query/enable-broadcast.ts","../src/support-bfcache.ts","../src/functions/propmods/add.ts","../src/functions/propmods/remove.ts","../src/functions/propmods/replace-prefix.ts","../src/index.ts","../src/index-umd.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _global }\n\nexport function extend(obj: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _slice = [].slice;\nexport function slice(args, start?, end?) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn: (...args: any[])=>void, onerror, args?) : void {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj == null ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath)) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = new Set(intrinsicTypeNames.map(t=>_global[t]));\n\n/** Deep clone a simple object tree.\n * \n * Copies object tree deeply, but does not deep-copy arrays,\n * typed arrays, Dates or other intrinsic types.\n * \n * Does not check for cyclic references.\n * \n * This function is 6 times faster than structuredClone() on chromium 111.\n * \n * This function can safely be used for cloning ObservabilitySets and RangeSets.\n * \n * @param o Object to clone\n * @returns Cloned object\n */\nexport function cloneSimpleObjectTree(o: T): T {\n const rv = {} as T;\n for (const k in o) if (hasOwn(o, k)) {\n const v = o[k];\n rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v);\n }\n return rv;\n}\n\nexport function objectIsEmpty(o: object) {\n for (const k in o) if (hasOwn(o, k)) return false;\n return true;\n}\n\nlet circularRefs: null | WeakMap = null;\n\n/** Deep clone an object or array.\n * \n * \n * @param any \n * @returns \n */\nexport function deepClone(any: T): T {\n circularRefs = new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(x: T): T {\n if (!x || typeof x !== 'object') return x;\n let rv = circularRefs.get(x); // Resolve circular references\n if (rv) return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n } else if (intrinsicTypes.has(x.constructor)) {\n // For performance, we're less strict than structuredClone - we're only\n // cloning arrays and custom objects.\n // Typed arrays, Dates etc are not cloned.\n rv = x;\n } else {\n // We're nicer to custom classes than what structuredClone() is -\n // we preserve the proto of each object.\n const proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n}\n\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\n\nexport function delArrayItem(a: any[], x: any) {\n const i = a.indexOf(x);\n if (i >= 0) a.splice(i, 1);\n return i >= 0;\n}\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\n","import { derive, setProp } from '../functions/utils';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n}\n\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See https://dexie.org/docs/Deprecations}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport { _global } from '../globals/global';\nimport {tryCatch, props, setProp,\n getPropertyDescriptor, getArrayOf, extend, getProto} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\nconst\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nfunction schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n}\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function DexiePromise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\n resolve,\n reject,\n psd));\n });\n if (this._consoleTask) rv._consoleTask = this._consoleTask;\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n return DexiePromise.resolve(onFinally()).then(()=>value);\n }, err => {\n return DexiePromise.resolve(onFinally()).then(()=>PromiseReject(err));\n });\n },\n \n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\n if (NativePromise.withResolvers) DexiePromise.withResolvers = NativePromise.withResolvers;\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (!promise._state && rejectingErrors.length) rejectingErrors = [];\n // cb is onResolved\n ret = debug && promise._consoleTask ? promise._consoleTask.run(()=>cb (value)) : cb (value);\n if (!promise._state && rejectingErrors.indexOf(value) === -1) {\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\n/* The callback to schedule with queueMicrotask().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n usePSD(globalPSD, ()=>{\n // Make sure to reset the async context to globalPSD before\n // executing any of the microtick subscribers.\n beginMicroTickScope() && endMicroTickScope();\n });\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // When > 0, zoneLeaveEcho is queued. When 0 and task.echoes is also 0, nothing is queued.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits() {\n if (!task.awaits) return false;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n return true;\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n //if (task.echoes === 1) console.warn(\"Cancelling echoing of async context.\");\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.awaits = task.id = 0; // Cancel echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n if (cleanup) queueMicrotask(decrementExpectedAwaits);\n }\n };\n}\n\n/** Execute callback in global context */\nexport function execInGlobalContext(cb) {\n if (Promise === NativePromise && task.echoes === 0) {\n if (zoneEchoes === 0) {\n cb();\n } else {\n enqueueNativeMicroTask(cb);\n }\n } else {\n setTimeout(cb, 0);\n }\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { errnames, exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._state.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db.close({disableAutoOpen: false});\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n if (mode === 'readwrite') try {trans.idbtrans.commit();} catch {}\n return mode === 'readonly' ? result : trans._completion.then(() => result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\n}","import { exceptions } from \"../../errors\";\n\nexport function Entity(){\n throw exceptions.Type();\n}\n","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array\n | BigInt64Array \n | BigUint64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, setByKeyPath, extend, getProto } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\nimport { Entity } from '../entity/Entity';\nimport { UpdateSpec } from '../../public';\nimport { cmp } from '../../functions/cmp';\n\n/** class Table\n * \n * https://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n // @ts-ignore: Use Chrome's Async Stack Tagging API to allow tracing and simplify debugging for dexie users.\n const task = debug && typeof console !== 'undefined' && console.createTask && console.createTask(`Dexie: ${mode === 'readonly' ? 'read' : 'write' } ${this.name}`);\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans) as Promise;\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n let p = trans && trans.db._novip === this.db._novip ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n if (task) { // Dexie.debug = true so we trace errors\n p._consoleTask = task;\n p = p.catch(err => {\n console.trace(err);\n return rejection(err);\n });\n }\n return p; \n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * https://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n if (keyOrCrit == null) return rejection(new exceptions.Type(`Invalid argument to Table.get()`));\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * https://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => {\n if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[0];\n \n if (compoundIndex && this.db._maxKey !== maxString) {\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit from a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n\n function equals(a, b) {\n return cmp(a, b) === 0; // Works with all indexable types including binary keys.\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * https://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * https://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * https://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * https://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * https://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * https://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * https://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * https://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n const {db, name: tableName} = this;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = class extends (constructor as any) {\n get db () { return db; }\n table() { return tableName; }\n }\n }\n // Collect all inherited property names (including method names) by\n // walking the prototype chain. This is to avoid overwriting them from\n // database data - so application code can rely on inherited props never\n // becoming shadowed by database object props.\n const inheritedProps = new Set();\n for (let proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName));\n }\n \n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n const readHook = (obj: Object) => {\n if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.\n // Create a new object that derives from constructor:\n const res = Object.create(constructor.prototype);\n // Clone members (but never those that collide with a property in the prototype\n // hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):\n for (let m in obj) if (!inheritedProps.has(m)) try { res[m] = obj[m]; } catch (_) { }\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n /*// object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly. TODO: Document this change!\n if (!Object.isFrozen(keyOrObject)) try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }*/\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n\n /** Table.put()\n * \n * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * https://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * https://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * https://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkUpdate()\n *\n * https://dexie.org/docs/Table.Table.bulkUpdate()\n */\n bulkUpdate(\n keysAndChanges: readonly { key: any; changes: UpdateSpec }[]\n ): PromiseExtended {\n const coreTable = this.core;\n const keys = keysAndChanges.map((entry) => entry.key);\n const changeSpecs = keysAndChanges.map((entry) => entry.changes);\n const offsetMap: number[] = [];\n return this._trans('readwrite', (trans) => {\n return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keysAndChanges.forEach(({ key, changes }, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const keyPath of Object.keys(changes)) {\n const value = changes[keyPath];\n if (keyPath === this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\n `Cannot update primary key in bulkUpdate()`\n );\n }\n } else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n const numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys,\n changeSpecs\n }\n })\n .then(({ numFailures, failures }) => {\n if (numFailures === 0) return numEntries;\n // Failure. bulkPut() may have a subset of keys\n // so we must translate returned 'failutes' into the offsets of given argument:\n for (const offset of Object.keys(failures)) {\n const mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n const failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\n `${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,\n failures\n );\n });\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/chaining-functions';\nimport {exceptions} from '../errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { isArray } from \"../functions/utils\";\nimport { PropModSpec } from \"../public/types/prop-modification\";\n\nexport const PropModSymbol: unique symbol = Symbol();\n\n/** Consistent change propagation across offline synced data.\n * \n * This class is executed client- and server side on sync, making\n * an operation consistent across sync for full consistency and accuracy.\n * \n * Example: An object represents a bank account with a balance.\n * One offline user adds $ 1.00 to the balance.\n * Another user (online) adds $ 2.00 to the balance.\n * When first user syncs, the balance becomes the sum of every operation (3.00).\n * \n * -- initial: balance is 0\n * 1. db.bankAccounts.update(1, { balance: new ProdModification({add: 100})}) // user 1 (offline)\n * 2. db.bankAccounts.update(1, { balance: new ProdModification({add: 200})}) // user 2 (online)\n * -- before user 1 syncs, balance is 200 (representing money with integers * 100 to avoid rounding issues)\n * \n * -- balance is 300\n * \n * When new operations are added, they need to be added to:\n * 1. PropModSpec interface\n * 2. Here in PropModification with the logic they represent\n * 3. (Optionally) a sugar function for it, such as const mathAdd = (amount: number | BigInt) => new PropModification({mathAdd: amount})\n */\nexport class PropModification implements PropModSpec {\n [PropModSymbol]?: true;\n replacePrefix?: [string, string];\n add?: number | bigint | Array;\n remove?: number | bigint | Array;\n\n execute(value: any): any {\n // add (mathematical or set-wise)\n if (this.add !== undefined) {\n const term = this.add;\n // Set-addition on array representing a set of primitive types (strings, numbers)\n if (isArray(term)) {\n return [...(isArray(value) ? value : []), ...term].sort();\n }\n // Mathematical addition:\n if (typeof term === 'number') return (Number(value) || 0) + term; // if value is not convertible to number, return 0 + term\n if (typeof term === 'bigint') {\n try {\n return BigInt(value) + term;\n } catch {\n return BigInt(0) + term; // Unlike Number(value) that can return NaN, BigInt(value) throws if value is not BigInt, Number or numeric string\n }\n }\n throw new TypeError(`Invalid term ${term}`);\n }\n\n // remove (mathematical or set-wise)\n if (this.remove !== undefined) {\n const subtrahend = this.remove;\n // Set-addition on array representing a set of primitive types (strings, numbers)\n if (isArray(subtrahend)) {\n return isArray(value) ? value.filter(item => !subtrahend.includes(item)).sort() : [];\n } \n // Mathematical addition:\n if (typeof subtrahend === 'number') return Number(value) - subtrahend;\n if (typeof subtrahend === 'bigint') {\n try {\n return BigInt(value) - subtrahend;\n } catch {\n return BigInt(0) - subtrahend; // Unlike Number(value) that can return NaN, BigInt(value) throws if value is not BigInt, Number or numeric string\n }\n }\n throw new TypeError(`Invalid subtrahend ${subtrahend}`);\n }\n\n // Replace a prefix:\n const prefixToReplace = this.replacePrefix?.[0];\n if (prefixToReplace && typeof value === 'string' && value.startsWith(prefixToReplace)) {\n return this.replacePrefix[1] + value.substring(prefixToReplace.length);\n }\n return value;\n }\n\n constructor(spec: PropModSpec) {\n Object.assign(this, spec);\n }\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\nimport { cmp } from \"../../functions/cmp\";\nimport { PropModification } from \"../../helpers/prop-modification\";\nimport { UpdateSpec } from \"../../public/types/update-spec\";\n\n/** class Collection\n * \n * https://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * https://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(props?): this {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n\n /** Collection.raw()\n * \n * https://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw(): this {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * https://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * https://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * https://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return cmp(aVal, bVal) * order;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n\n /** Collection.toArray()\n * \n * https://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * https://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * https://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n }\n\n /** Collection.until()\n * \n * https://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n }\n\n /** Collection.first()\n * \n * https://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n\n /** Collection.and()\n * \n * https://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * https://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * https://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n }\n\n /** Collection.desc()\n * \n * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * https://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.primaryKeys()\n * \n * https://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.uniqueKeys()\n * \n * https://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * https://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor: DBCoreCursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n\n //\n // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * https://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: UpdateSpec | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n modifyer = changes as (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean;\n } else {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n let anythingModified = false;\n for (let i = 0; i < numKeys; ++i) {\n let keyPath = keyPaths[i];\n let val = changes[keyPath];\n let origVal = getByKeyPath(item, keyPath);\n\n if (val instanceof PropModification) {\n setByKeyPath(item, keyPath, val.execute(origVal));\n anythingModified = true;\n } else if (origVal !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n let limit = 200;\n const modifyChunkSize = this.db._options.modifyChunkSize;\n if (modifyChunkSize) {\n if (typeof modifyChunkSize == 'object') {\n limit = modifyChunkSize[coreTable.name] || modifyChunkSize['*'] || 200;\n } else {\n limit = modifyChunkSize;\n }\n }\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n const criteria = isPlainKeyRange(ctx) &&\n ctx.limit === Infinity &&\n (typeof changes !== 'function' || changes === deleteCallback) && {\n index: ctx.index,\n range: ctx.range\n };\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes,\n isAdditionalChunk: offset > 0\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria,\n isAdditionalChunk: offset > 0\n }).then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * https://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n (ctx.isPrimKey || range.type === DBCoreRangeType.Any)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\n\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix)\n );\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * https://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\nimport { cmp } from '../../functions/cmp';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n this._cmp = this._ascending = cmp;\n this._descending = (a, b) => cmp(b, a);\n this._max = (a, b) => cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange) throw new exceptions.MissingAPI();\n }\n );\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nexport function hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\n idbtrans: IDBTransaction;\n storeNames: string[];\n explicit?: boolean;\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n }\n\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction & {[prop: string]: any}) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): https://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n };\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results: [], lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\nimport { debug } from '../../helpers/debug';\nimport { PromiseExtended } from '../../public/types/promise-extended';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n if (idbUpgradeTrans.objectStoreNames.contains('$meta') && !globalSchema.$meta) {\n globalSchema.$meta = createTableSchema(\"$meta\", parseIndexSyntax(\"\")[0], []);\n db._storeNames.push('$meta');\n }\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else {\n generateMiddlewareStacks(db, idbUpgradeTrans);\n return getExistingVersion(db, trans, oldVersion)\n .then(oldVersion => updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans))\n .catch(rejectTransaction);\n }\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function patchCurrentVersion(db: Dexie, idbUpgradeTrans: IDBTransaction) {\n createMissingTables(db._dbSchema, idbUpgradeTrans);\n if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) {\n // Rolled over to the next 10-ies due to many schema upgrades without bumping version.\n // No problem! We pin the database to its expected version by adding the $meta table so that next\n // time the programmer bumps the version and attaches, an upgrader, that upgrader will indeed run,\n // as well any further upgraders coming after that.\n idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version');\n }\n const globalSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n adjustToExistingIndexNames(db, db._dbSchema, idbUpgradeTrans);\n const diff = getSchemaDiff(globalSchema, db._dbSchema);\n for (const tableChange of diff.change) {\n if (tableChange.change.length || tableChange.recreate) {\n console.warn(`Unable to patch indexes of table ${tableChange.name} because it has changes on the type of index or primary key.`);\n return;\n }\n const store = idbUpgradeTrans.objectStore(tableChange.name);\n tableChange.add.forEach(idx => {\n if (debug) console.debug(`Dexie upgrade patch: Creating missing index ${tableChange.name}.${idx.src}`);\n addIndex(store, idx);\n });\n }\n}\n\nfunction getExistingVersion(db: Dexie, trans: Transaction, oldVersion: number): PromiseExtended {\n // In normal case, existing version is the native installed version divided by 10.\n // However, in case more than 10 schema changes have been made on the same version (such as while\n // developing an app), the native version may have passed beyond a multiple of 10 within the same version.\n // When that happens, a table $meta will have been created, containing a single entry with key \"version\"\n // and the value of the real old version to use when running upgraders going forward.\n if (trans.storeNames.includes('$meta')) {\n return trans.table('$meta').get('version').then(metaVersion => {\n return metaVersion != null ? metaVersion : oldVersion\n })\n } else {\n return Promise.resolve(oldVersion);\n }\n}\n\nfunction updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n \n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n if (versToRun.length === 0) {\n // Important not to continue at this point.\n // Coming here means we've already patched schema in patchCurrentVersion() after having\n // incremented native version to a value above the declared highest version.\n // When being in this mode, it means that there might be different versions the db competing\n // about it with different version of the schema. Therefore, we must avoid deleting tables\n // or indexes here so that both versions can co-exist until the application has been upgraded to\n // a version that declares no lower than the native version.\n // If after that, a downgrade happens again, we'll end up here again, accepting both versions\n // And we'll stay in this state until app developer releases a new declared version.\n return Promise.resolve(); \n }\n \n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n // Maintain the $meta table after this version's tables and indexes has been created and content upgraders have run.\n queue.push(idbtrans => {\n if (db.idbdb.objectStoreNames.contains('$meta')) {\n if (Math.ceil(db.idbdb.version / 10) === version._cfg.version) {\n // Remove $meta table if it's no more needed - we are in line with the native version\n db.idbdb.deleteObjectStore('$meta');\n delete db._dbSchema.$meta;\n db._storeNames = db._storeNames.filter(name => name !== '$meta');\n } else {\n // We're still not in line with the native version. Make sure to update the virtual version\n // to the successfully run version\n idbtrans.objectStore('$meta').put(version._cfg.version, 'version');\n }\n }\n }); \n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto))\n {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\n\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n if (debug) console.debug('Dexie: Creating missing table', tableName);\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\n\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n true,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n primKey.unique = true;\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string | null; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n infos\n // Select name prop of infos:\n .map((info) => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter((name) => name !== DBNAMES_DB)\n )\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n}\n\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n hasKey(key: IndexableType) {\n const node = getRangeSetIterator(this).next(key).value;\n return node && cmp(node.from, key) <= 0 && cmp(node.to, key) >= 0;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { cloneSimpleObjectTree, deepClone, keys, objectIsEmpty } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n if (target[part]) mergeRanges(target[part], newSet[part]);\n else target[part] = cloneSimpleObjectTree(newSet[part]); // Somewhat faster\n });\n return target;\n}\n","import { rangesOverlap } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function obsSetsOverlap(os1: ObservabilitySet, os2: ObservabilitySet) {\n return os1.all || os2.all || Object.keys(os1).some(\n (key) => os2[key] && rangesOverlap(os2[key], os1[key])\n );\n}\n","import { type GlobalQueryCache } from \"../../public/types/cache\";\n\nexport const cache: GlobalQueryCache = {}\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport { extendObservabilitySet } from '../extend-observability-set';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { cache } from './cache';\n\nlet unsignaledParts: ObservabilitySet = {};\nlet isTaskEnqueued = false;\n\nexport function signalSubscribersLazily(part: ObservabilitySet, optimistic = false) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(() => {\n isTaskEnqueued = false;\n const parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts, false);\n }, 0);\n }\n}\n\nexport function signalSubscribersNow(\n updatedParts: ObservabilitySet,\n deleteAffectedCacheEntries = false\n) {\n const queriesToSignal = new Set<() => void>();\n if (updatedParts.all) {\n // Signal all subscribers to requery.\n for (const tblCache of Object.values(cache)) {\n collectTableSubscribers(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n } else {\n for (const key in updatedParts) {\n const parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n const [, dbName, tableName] = parts;\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (tblCache)\n collectTableSubscribers(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n }\n }\n // Now when affected cache entries are removed, signal collected subscribers to requery.\n queriesToSignal.forEach((requery) => requery());\n}\n\nfunction collectTableSubscribers(\n tblCache: TblQueryCache,\n updatedParts: ObservabilitySet,\n outQueriesToSignal: Set<() => void>,\n deleteAffectedCacheEntries: boolean\n) {\n const updatedEntryLists: [string, CacheEntry[]][] = [];\n for (const [indexName, entries] of Object.entries(tblCache.queries.query)) {\n const filteredEntries: CacheEntry[] = [];\n for (const entry of entries) {\n if (obsSetsOverlap(updatedParts, entry.obsSet)) {\n // This query is affected by the mutation. Remove it from cache\n // and signal all subscribers to requery.\n entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery));\n } else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n // Collect cache entries to be updated\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (const [indexName, filteredEntries] of updatedEntryLists) {\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n}\n","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames, verifyInstalledSchema, patchCurrentVersion } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\nimport safari14Workaround from 'safari-14-idb-fix';\nimport { type ObservabilitySet } from '../../public/types/db-events';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { DEXIE_STORAGE_MUTATED_EVENT_NAME, globalEvents } from '../../globals/global-events';\nimport { signalSubscribersNow } from '../../live-query/cache/signalSubscribers';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n let nativeVerToOpen = Math.round(db.verno * 10);\n let schemaPatchMode = false;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null,\n wasCreated = false;\n\n const tryOpenDB = () => new Promise((resolve, reject) => {\n throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\n const dbName = db.name;\n \n const req = state.autoSchema || !nativeVerToOpen ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, nativeVerToOpen);\n if (!req) throw new exceptions.MissingAPI(); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n const oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n if (schemaPatchMode) {\n patchCurrentVersion(db, upgradeTransaction);\n }\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans) && !schemaPatchMode) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this.`);\n idbdb.close();\n nativeVerToOpen = idbdb.version + 1;\n schemaPatchMode = true;\n return resolve (tryOpenDB()); // Try again with new version (nativeVerToOpen\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }).catch(err => {\n switch (err?.name) {\n case \"UnknownError\":\n if (state.PR1398_maxLoop > 0) {\n // Bug in Chrome after clearing site data\n // https://github.com/dexie/Dexie.js/issues/543#issuecomment-1795736695\n state.PR1398_maxLoop--;\n console.warn('Dexie: Workaround for Chrome UnknownError on open()');\n return tryOpenDB();\n }\n break;\n case \"VersionError\":\n if (nativeVerToOpen > 0) {\n nativeVerToOpen = 0;\n return tryOpenDB();\n }\n break;\n }\n return Promise.reject(err);\n });\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([\n openCanceller,\n (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(tryOpenDB)\n ]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>remainders(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n if (state.openCanceller === openCanceller) {\n // Only modify state if not cancelled in the mean time.\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n }).then(()=>{\n if (wasCreated) {\n // Propagate full range on primary keys and indexes on all tables now that the DB is ready and opened,\n // and all upgraders and on('ready') subscribers have run.\n const everything: ObservabilitySet = {};\n db.tables.forEach(table => {\n table.schema.indexes.forEach(idx => {\n if (idx.name) everything[`idb://${db.name}/${table.name}/${idx.name}`] = new RangeSet(-Infinity, [[[]]]);\n });\n everything[`idb://${db.name}/${table.name}/`] = everything[`idb://${db.name}/${table.name}/:dels`] = new RangeSet(-Infinity, [[[]]]);\n });\n // Database was created. If another tab had it open when it was deleted and reopened, that tab must be updated now.\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything);\n // Wipe the cache and trigger optimistic queries:\n signalSubscribersNow(everything, true);\n }\n // Resolve the db.open() with the db instance.\n return db;\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { errnames, exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n trans.explicit = true;\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n // @ts-ignore Mark the idbtrans object with \"_explicit\". DBCore middleware won't have access to Dexie trans but will need to have this info.\n trans.idbtrans._explicit = true;\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db.close({disableAutoOpen: false});\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\n }\n\n // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n}\n","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n\n /** LowLevelIndex represents the actual IndexedDB index behind it */\n lowLevelIndex: DBCoreIndex;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n name: isVirtual\n ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})`\n : lowLevelIndex.name,\n lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys} :\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: readonly any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { DBCore, DBCoreTable } from '../../public/types/dbcore';\nimport { LiveQueryContext } from '../live-query';\n\nexport function isCachableContext(ctx: LiveQueryContext, table: DBCoreTable) {\n return (\n ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound\n );\n}\n\n","import { DBCoreCountRequest, DBCoreGetManyRequest, DBCoreGetRequest, DBCoreOpenCursorRequest, DBCoreQueryRequest } from '../../public/types/dbcore';\n\n\nexport function isCachableRequest(type: string, req: Partial) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n}\n","import { LiveQueryContext } from \".\";\nimport { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { getEffectiveKeys } from \"../dbcore/get-effective-keys\";\nimport { exceptions } from \"../errors\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport { isCachableContext } from \"./cache/is-cachable-context\";\nimport { isCachableRequest } from \"./cache/is-cachable-request\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n name: \"Observability\",\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n transaction: (stores, mode, options) => {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${(PSD as LiveQueryContext).querier}`);\n }\n return core.transaction(stores, mode, options);\n },\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey, indexes } = schema;\n const { extractKey, outbound } = primaryKey;\n const indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(\n (index) => index.compound && (index.keyPath as string[]).includes(primaryKey.keyPath as string)\n );\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [getEffectiveKeys(primaryKey, req).filter(id => id), req.values] // keys except autoIncremented - they will be added later on.\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n\n const oldCache = req.trans[\"_cache\"];\n\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n // Individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null;\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs) {\n // add, delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() and primaryKeys() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // keys is a DBCoreKeyRange object. Transform it to [from,to]-style range.\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n // (above/below-style ranges are not supported in RangeSet.ts, so we must replace open ends\n // with core.MIN_KEY and core.MAX_KEY respectively. This is what solves issue #2067!\n const range = {\n from: keys.lower ?? core.MIN_KEY,\n to: keys.upper ?? core.MAX_KEY\n };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n\n return table.mutate(req).then((res) => {\n // Merge the mutated parts from the request into the transaction's mutatedParts\n // now when the request went fine.\n if (keys && (req.type === 'add' || req.type === 'put')) {\n // Less than 50 requests (keys truthy) (otherwise we've added full range anyway)\n // autoincrement means we might not have got all keys until now\n pkRangeSet.addKeys(res.results);\n if (indexesWithAutoIncPK) {\n // Dexie Issue 1946:\n // If an auto-incremented primary key is part of a compound index,\n // we need to compute the resulting value of that index after inserting\n // the rows.\n indexesWithAutoIncPK.forEach(idx => {\n // Extract values of this compound index where primary key is not yet set:\n const idxVals = req.values.map(v => idx.extractKey(v));\n // Find the position of the primary key in the index:\n const pkPos = (idx.keyPath as string[]).findIndex(prop => prop === primaryKey.keyPath);\n // Update idxVals with the resulting primary keys to complete the index value:\n for (let i = 0, len = res.results!.length; i < len; ++i) {\n idxVals[i][pkPos] = res.results![i];\n }\n // Add the updated index to the rangeset:\n getRangeSet(idx.name).addKeys(idxVals);\n });\n }\n }\n trans.mutatedParts = extendObservabilitySet (\n trans.mutatedParts || {},\n mutatedParts\n );\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach((method: 'get' | 'getMany' | 'count' | 'query' | 'openCursor') => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD as LiveQueryContext;\n const isLiveQuery = !!subscr;\n let cachable = isCachableContext(PSD as LiveQueryContext, table) && isCachableRequest(method, req);\n const obsSet = cachable\n ? req.obsSet = {} // Implicit read transaction - track changes for this query only for the request's duration\n : subscr; // Explicit read transaction - track changes across entire live query\n\n if (isLiveQuery) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n if (method === 'query' && queriedIndex.isPrimaryKey && !(req as DBCoreQueryRequest).values) {\n // A pure primay-key based Collection where only .primaryKeys() is requested. Don't wakeup on other changes than added or deleted primary keys within queried range.\n delsRangeSet.add(queriedRanges);\n } else {\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n }\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: readonly any[] | undefined,\n newObjs: readonly any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n","import { delArrayItem, isArray } from '../../functions/utils';\nimport { TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreMutateRequest,\n DBCoreMutateResponse,\n} from '../../public/types/dbcore';\n\nexport function adjustOptimisticFromFailures(\n tblCache: TblQueryCache,\n req: DBCoreMutateRequest,\n res: DBCoreMutateResponse\n): DBCoreMutateRequest {\n if (res.numFailures === 0) return req;\n if (req.type === 'deleteRange') {\n // numFailures > 0 means the deleteRange operation failed in its whole.\n return null;\n }\n\n const numBulkOps = req.keys\n ? req.keys.length\n : 'values' in req && req.values\n ? req.values.length\n : 1;\n if (res.numFailures === numBulkOps) {\n // Same number of failures as the number of ops. This means that all ops failed.\n return null;\n }\n\n const clone: DBCoreMutateRequest = { ...req };\n\n if (isArray(clone.keys)) {\n clone.keys = clone.keys.filter((_, i) => !(i in res.failures));\n }\n if ('values' in clone && isArray(clone.values)) {\n clone.values = clone.values.filter((_, i) => !(i in res.failures));\n }\n return clone;\n}\n","import { cmp } from '../../functions/cmp';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function isAboveLower(key: IndexableType, range: DBCoreKeyRange) {\n return range.lower === undefined\n ? true // lower is less than anything because it is undefined\n : range.lowerOpen\n ? cmp(key, range.lower) > 0 // lowerOpen: Exclude lower bound\n : cmp(key, range.lower) >= 0; // !lowerOpen: Include lower bound\n}\n\nexport function isBelowUpper(key: IndexableType, range: DBCoreKeyRange) {\n return range.upper === undefined\n ? true // upper is greater than anything because it is undefined\n : range.upperOpen\n ? cmp(key, range.upper) < 0 // upperOpen: Exclude upper bound\n : cmp(key, range.upper) <= 0; // !upperOpen: Include upper bound\n}\n\nexport function isWithinRange(key: IndexableType, range: DBCoreKeyRange) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n}\n","import { cmp } from '../../functions/cmp';\nimport { isArray } from '../../functions/utils';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { CacheEntry } from '../../public/types/cache';\nimport {\n DBCoreMutateRequest,\n DBCoreQueryRequest,\n DBCoreTable,\n} from '../../public/types/dbcore';\nimport { isWithinRange } from './is-within-range';\n\nexport function applyOptimisticOps(\n result: any[],\n req: DBCoreQueryRequest,\n ops: DBCoreMutateRequest[] | undefined,\n table: DBCoreTable,\n cacheEntry: CacheEntry,\n immutable: boolean\n): any[] {\n if (!ops || ops.length === 0) return result;\n const index = req.query.index;\n const { multiEntry } = index;\n const queryRange = req.query.range;\n const primaryKey = table.schema.primaryKey;\n const extractPrimKey = primaryKey.extractKey!;\n const extractIndex = index.extractKey!;\n const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey!;\n\n let finalResult = ops.reduce((result, op) => {\n let modifedResult = result;\n const includedValues: any[] = [];\n if (op.type === 'add' || op.type === 'put') {\n const includedPKs = new RangeSet(); // For ignoring duplicates\n for (let i = op.values.length - 1; i >= 0; --i) {\n // backwards to prioritize last value of same PK\n const value = op.values[i];\n const pk = extractPrimKey(value);\n if (includedPKs.hasKey(pk)) continue;\n const key = extractIndex(value);\n if (\n multiEntry && isArray(key)\n ? key.some((k) => isWithinRange(k, queryRange))\n : isWithinRange(key, queryRange)\n ) {\n includedPKs.addKey(pk);\n includedValues.push(value);\n }\n }\n }\n switch (op.type) {\n case 'add': {\n const existingKeys = new RangeSet().addKeys(\n req.values ? result.map((v) => extractPrimKey(v)) : result\n );\n\n modifedResult = result.concat(\n req.values\n ? includedValues.filter((v) => {\n const key = extractPrimKey(v);\n if (existingKeys.hasKey(key)) return false;\n existingKeys.addKey(key);\n return true;\n })\n : includedValues\n .map((v) => extractPrimKey(v))\n .filter((k) => {\n if (existingKeys.hasKey(k)) return false;\n existingKeys.addKey(k);\n return true;\n })\n );\n break;\n }\n case 'put': {\n const keySet = new RangeSet().addKeys(\n op.values.map((v) => extractPrimKey(v))\n );\n modifedResult = result\n .filter(\n // Remove all items that are being replaced\n (item) => !keySet.hasKey(req.values ? extractPrimKey(item) : item)\n )\n .concat(\n // Add all items that are being put (sorting will be done later)\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n }\n case 'delete':\n const keysToDelete = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter(\n (item) =>\n !keysToDelete.hasKey(req.values ? extractPrimKey(item) : item)\n );\n\n break;\n case 'deleteRange':\n const range = op.range;\n modifedResult = result.filter(\n (item) => !isWithinRange(extractPrimKey(item), range)\n );\n break;\n }\n return modifedResult;\n }, result);\n\n // If no changes were made, we can return the original result.\n if (finalResult === result) return result;\n\n // Sort the result on sortIndex:\n finalResult.sort((a, b) =>\n cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b))\n );\n\n // If we have a limit we need to respect it:\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit; // Cut of any extras after sorting correctly.\n } else if (result.length === req.limit && finalResult.length < req.limit) {\n // We're missing some items because of the limit. We need to add them back.\n // The easiest way is to mark the cache entry as dirty, which will cause\n // it to be requeried after the write-transaction successfully completes.\n cacheEntry.dirty = true;\n }\n }\n return immutable ? Object.freeze(finalResult) as any[] : finalResult;\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function areRangesEqual(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen\n );\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function compareLowers(lower1: any, lower2: any, lowerOpen1: boolean, lowerOpen2: boolean) {\n if (lower1 === undefined) return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined) return 1; // since lower1 !== undefined\n const c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2) return 0;\n if (lowerOpen1) return 1\n if (lowerOpen2) return -1;\n }\n return c;\n}\n\nexport function compareUppers(upper1: any, upper2: any, upperOpen1: boolean, upperOpen2: boolean) {\n if (upper1 === undefined) return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined) return -1; // since upper1 !== undefined\n const c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2) return 0;\n if (upperOpen1) return -1\n if (upperOpen2) return 1;\n }\n return c;\n}\n\nexport function isSuperRange(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0\n );\n}","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreCountRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\nimport { areRangesEqual } from './are-ranges-equal';\nimport { cache } from './cache';\nimport { isSuperRange } from './is-super-range';\n\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query',\n req: DBCoreQueryRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'count',\n req: DBCoreCountRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query' | 'count',\n req: Partial & Partial\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]] {\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return [];\n const queries = tblCache.queries[type];\n if (!queries) return [null, false, tblCache, null];\n const indexName = req.query ? req.query.index.name : null;\n const entries = queries[indexName || ''];\n if (!entries) return [null, false, tblCache, null];\n\n switch (type) {\n case 'query':\n const equalEntry = entries.find(\n (entry) =>\n (entry.req as DBCoreQueryRequest).limit === req.limit &&\n (entry.req as DBCoreQueryRequest).values === req.values &&\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n if (equalEntry)\n return [\n equalEntry,\n true, // exact match\n tblCache,\n entries,\n ];\n const superEntry = entries.find((entry) => {\n const limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (\n limit >= req.limit &&\n (req.values ? (entry.req as DBCoreQueryRequest).values : true) &&\n isSuperRange(entry.req.query.range, req.query.range)\n );\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n const countQuery = entries.find((entry) =>\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n return [countQuery, !!countQuery, tblCache, entries];\n }\n}\n","import { delArrayItem } from \"../../functions/utils\";\nimport { CacheEntry } from \"../../public/types/cache\";\n\nexport function subscribeToCacheEntry(cacheEntry: CacheEntry, container: CacheEntry[], requery: ()=>void, signal: AbortSignal) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener(\"abort\", () => {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n}\n\n\nfunction enqueForDeletion(cacheEntry: CacheEntry, container: CacheEntry[]) {\n setTimeout(() => {\n if (cacheEntry.subscribers.size === 0) { // Still empty (no new subscribers readded after grace time)\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n}\n","import { LiveQueryContext } from '..';\nimport type { Transaction } from '../../classes/transaction';\nimport { getEffectiveKeys } from '../../dbcore/get-effective-keys';\nimport { deepClone, delArrayItem, setByKeyPath } from '../../functions/utils';\nimport DexiePromise, { PSD } from '../../helpers/promise';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport {\n DBCore, DBCoreMutateRequest, DBCoreMutateResponse, DBCoreQueryRequest,\n DBCoreQueryResponse\n} from '../../public/types/dbcore';\nimport { Middleware } from '../../public/types/middleware';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { adjustOptimisticFromFailures } from './adjust-optimistic-request-from-failures';\nimport { applyOptimisticOps } from './apply-optimistic-ops';\nimport { cache } from './cache';\nimport { findCompatibleQuery } from './find-compatible-query';\nimport { isCachableContext } from './is-cachable-context';\nimport { isCachableRequest } from './is-cachable-request';\nimport { signalSubscribersLazily } from './signalSubscribers';\nimport { subscribeToCacheEntry } from './subscribe-cachentry';\n\nexport const cacheMiddleware: Middleware = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: (core) => {\n const dbName = core.schema.name;\n const coreMW: DBCore = {\n ...core,\n transaction: (stores, mode, options) => {\n const idbtrans = core.transaction(\n stores,\n mode,\n options\n ) as IDBTransaction & {\n mutatedParts?: ObservabilitySet;\n _explicit?: boolean;\n };\n // Maintain TblQueryCache.ops array when transactions commit or abort\n if (mode === 'readwrite') {\n const ac = new AbortController();\n const { signal } = ac;\n const endTransaction = (wasCommitted: boolean) => () => {\n ac.abort();\n if (mode === 'readwrite') {\n // Collect which subscribers to notify:\n const affectedSubscribers = new Set<()=>void>();\n\n // Go through all tables in transaction and check if they have any optimistic updates\n for (const storeName of stores) {\n const tblCache = cache[`idb://${dbName}/${storeName}`];\n if (tblCache) {\n const table = core.table(storeName);\n // Pick optimistic ops that are part of this transaction\n const ops = tblCache.optimisticOps.filter(\n (op) => op.trans === idbtrans\n );\n // Transaction was marked as _explicit in enterTransactionScope(), transaction-helpers.ts.\n if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {\n // Invalidate all queries that overlap with the mutated parts and signal their subscribers\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {\n delArrayItem(entries, entry); // Remove the entry from the cache so it can be refreshed\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n }\n }\n }\n } else if (ops.length > 0) {\n // Remove them from the optimisticOps array\n tblCache.optimisticOps = tblCache.optimisticOps.filter(\n (op) => op.trans !== idbtrans\n );\n // Commit or abort the optimistic updates\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n entry.res != null && // if entry.promise but not entry.res, we're fine. Query will resume now and get the result.\n idbtrans.mutatedParts/* &&\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)*/\n ) {\n if (wasCommitted && !entry.dirty) {\n const freezeResults = Object.isFrozen(entry.res);\n const modRes = applyOptimisticOps(\n entry.res as any[],\n entry.req,\n ops,\n table,\n entry,\n freezeResults\n );\n if (entry.dirty) {\n // Found out at this point that the entry is dirty - not to rely on!\n delArrayItem(entries, entry);\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n } else if (modRes !== entry.res) {\n entry.res = modRes;\n // Update promise\n entry.promise = DexiePromise.resolve({result: modRes} satisfies DBCoreQueryResponse);\n \n // No need to notify subscribers. They already have this value.\n // We have just updated the value of the cache without having to\n // requery the database - because we know the result for this\n // query based on computing the operations and applying them\n // to the previous result.\n }\n } else {\n if (entry.dirty) {\n // If the entry is dirty we need to get rid of it so that\n // a new entry will be created when the query is run again.\n delArrayItem(entries, entry);\n }\n // If we're not committing, we need to notify subscribers that the\n // optimistic updates are no longer valid.\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers.forEach((requery) => requery());\n }\n };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal,\n });\n }\n return idbtrans;\n },\n table(tableName: string) {\n const downTable = core.table(tableName);\n const primKey = downTable.schema.primaryKey;\n const tableMW = {\n ...downTable,\n mutate(req: DBCoreMutateRequest): Promise {\n const trans = PSD.trans as Transaction;\n if (\n primKey.outbound || // Non-inbound tables are harded to apply optimistic updates on because we can't know primary key of results\n trans.db._options.cache === 'disabled' || // User has opted-out from caching\n trans.explicit || // It's an explicit write transaction being made. Don't affect cache until transaction commits.\n trans.idbtrans.mode !== 'readwrite' // We only handle 'readwrite' in our transaction override. 'versionchange' transactions don't use cache (from populate or upgraders).\n ) {\n // Just forward the request to the core.\n return downTable.mutate(req);\n }\n // Find the TblQueryCache for this table:\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return downTable.mutate(req);\n\n const promise = downTable.mutate(req);\n if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(key => key == null))) {\n // There are some autoIncremented keys not set yet. Need to wait for completion before we can reliably enqueue the operation.\n // (or there are too many objects so we lazy out to avoid performance bottleneck for large bulk inserts)\n promise.then((res) => { // We need to extract result keys and generate cloned values with the keys set (so that applyOptimisticOps can work)\n // But we have a problem! The req.mutatedParts is still not complete so we have to actively add the keys to the unsignaledParts set manually.\n const reqWithResolvedKeys = {\n ...req,\n values: req.values.map((value, i) => {\n if (res.failures[i]) return value; // No need to rewrite a failing value\n const valueWithKey = primKey.keyPath?.includes('.')\n ? deepClone(value)\n : {\n ...value,\n };\n setByKeyPath(valueWithKey, primKey.keyPath, res.results![i]);\n return valueWithKey;\n })\n };\n const adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res);\n tblCache.optimisticOps.push(adjustedReq);\n // Signal subscribers after the observability middleware has complemented req.mutatedParts with the new keys.\n // We must queue the task so that we get the req.mutatedParts updated by observability middleware first.\n // If we refactor the dependency between observability middleware and this middleware we might not need to queue the task.\n queueMicrotask(()=>req.mutatedParts && signalSubscribersLazily(req.mutatedParts)); // Reason for double laziness: in user awaits put and then does another put, signal once.\n });\n } else {\n // Enque the operation immediately\n tblCache.optimisticOps.push(req);\n // Signal subscribers that there are mutated parts\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts);\n promise.then((res) => {\n if (res.numFailures > 0) {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n const adjustedReq = adjustOptimisticFromFailures(tblCache, req, res);\n if (adjustedReq) {\n tblCache.optimisticOps.push(adjustedReq);\n }\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n }\n });\n promise.catch(()=> {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n req.mutatedParts && signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n });\n }\n return promise;\n },\n query(req: DBCoreQueryRequest): Promise {\n if (!isCachableContext(PSD, downTable) || !isCachableRequest(\"query\", req)) return downTable.query(req);\n const freezeResults =\n (PSD as LiveQueryContext).trans?.db._options.cache === 'immutable';\n const { requery, signal } = PSD as LiveQueryContext;\n let [cacheEntry, exactMatch, tblCache, container] =\n findCompatibleQuery(dbName, tableName, 'query', req);\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet!; // So that optimistic result is monitored.\n // How? - because observability-middleware will track result where optimistic\n // mutations are applied and record it in the cacheEntry.\n // TODO: CHANGE THIS! The difference is resultKeys only.\n // Wanted behavior:\n // * cacheEntry obsSet should represent the obsSet without optimistic updates (so it can be checked when merging ops in tx commit)\n // * cacheEntry optimisticObsSet should represent the obsSet with current optimistic updates. It should be updated when adding an op\n // by adding the primary keys of the put/add/delete operation to the set.\n // * observability-middleware should stop recording req.obsSet when a cache entry exact match is found because it won't be used anyway.\n // I'm thinking of merging observability-middleware with cache-middleware into one single middleware because the dependencies are too\n // tight between them.\n } else {\n // --> TODO here: If not exact match, check if we have a superset to extract\n // the data from.\n\n // No cached result found. We need to query the database and cache the result.\n const promise = downTable.query(req).then((res) => {\n // Freeze or clone results\n const result = res.result;\n if (cacheEntry) cacheEntry.res = result;\n if (freezeResults) {\n // For performance reasons don't deep freeze.\n // Only freeze the top-level array and its items.\n // This is good enough to teach users that the result must be treated as immutable\n // without enforcing it recursively on the entire result (which is not even possible\n // for things like Date objects and typed arrays)\n for (let i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n } else {\n // If not frozen, we need to clone the result to avoid user mutating the cache\n // When we do this, user's must feel conformable with the fact that the result\n // can be mutated deeply - user is not expected to have any respect for immutability.\n res.result = deepClone(result);\n }\n return res;\n }).catch(error => {\n // In case the query operation failed, we need to remove it from the cache\n // so that subsequent calls does not get the same error but re-evaluate\n // the query.\n if (container && cacheEntry) delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet!,\n promise,\n subscribers: new Set(),\n type: 'query',\n req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n } else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[`idb://${dbName}/${tableName}`] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {}\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container!, requery, signal);\n return cacheEntry.promise.then((res: DBCoreQueryResponse) => {\n return {\n result: applyOptimisticOps(\n res.result,\n req,\n tblCache?.optimisticOps,\n downTable,\n cacheEntry!,\n freezeResults\n ) as any[], // readonly any[]\n };\n });\n },\n };\n return tableMW;\n },\n };\n return coreMW;\n },\n};\n\n\n","import { type Dexie } from \"../classes/dexie\";\nimport { type Table } from \"../classes/table\";\nimport { type Transaction } from \"../classes/transaction\";\n\nexport function vipify(\n target: T,\n vipDb: Dexie\n): T {\n return new Proxy(target, {\n get (target, prop, receiver) {\n // The \"db\" prop of the table or transaction is the only one we need to\n // override. The rest of the props can be accessed from the original\n // object.\n if (prop === 'db') return vipDb;\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD, globalPSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { _onDatabaseDeleted } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\nimport { cacheMiddleware } from \"../../live-query/cache/cache-middleware\";\nimport { vipify } from \"../../helpers/vipify\";\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n PR1398_maxLoop?: number;\n autoOpen?: boolean;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n _vip?: boolean;\n _novip: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n static disableBfCache?: boolean;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n cache: 'cloned', // Default to cloned for backward compatibility. For best performance and least memory consumption use 'immutable'.\n ...options\n }; \n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true,\n PR1398_maxLoop: 3,\n autoOpen: options.autoOpen,\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n const db = this;\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n this.on(\"versionchange\", ev => {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close({disableAutoOpen: false});\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n const vipDB = new Proxy(this, {\n get: (_, prop, receiver) => {\n if (prop === '_vip') return true;\n if (prop === 'table') return (tableName: string) => vipify(this.table(tableName), vipDB);\n const rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table) return vipify(rv, vipDB);\n if (prop === 'tables') return (rv as Table[]).map(t => vipify(t, vipDB));\n if (prop === '_createTransaction') return function() {\n const tx: Transaction = (rv as typeof this._createTransaction).apply(this, arguments);\n return vipify(tx, vipDB);\n }\n return rv;\n }\n });\n this.vip = vipDB;\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._state.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return usePSD(\n globalPSD, // Enforce global scope here since db.open() can be part of a live query or transaction scope\n () => dexieOpen(this)\n );\n }\n\n _close(): void {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n } \n // Reset dbReadyPromise promise:\n if (!state.isBeingOpened) {\n // Only if not being opened, reset these promises.\n // Otherwise, keep them so existing promise consumers will resolve when db\n // db is reopened later on, in case closing for purpose reopening, using {disableAutoOpen: false}.\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n }\n\n close({disableAutoOpen} = {disableAutoOpen: true}): void {\n const state = this._state;\n if (disableAutoOpen) {\n if (state.isBeingOpened) {\n // cancel before the call to this._close() because this._close() will recreate dbReadyPromise and openCanceller.\n state.cancelOpen(new exceptions.DatabaseClosed());\n }\n this._close();\n state.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n } else {\n this._close();\n state.autoOpen = this._options.autoOpen ||\n state.isBeingOpened; // If an open call is ongoing, that same promise will resolve when db is reopend.\n state.openComplete = false;\n state.dbOpenError = null;\n }\n }\n\n delete(closeOptions = {disableAutoOpen: true}): Promise {\n // Prevent accidentially doing db.delete(1) when intention was to do db.[table].delete(1).\n const hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== 'object'; \n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close(closeOptions);\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n // Prevent accidentially doing db.delete(1) when intention was to do db.[table].delete(1).\n if (hasInvalidArguments) throw new exceptions.InvalidArgument(\"Invalid closeOptions argument to db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { _global, isAsyncFunction, keys, objectIsEmpty } from '../functions/utils';\nimport {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport {\n beginMicroTickScope,\n decrementExpectedAwaits,\n endMicroTickScope,\n execInGlobalContext,\n incrementExpectedAwaits,\n NativePromise,\n newScope,\n PSD,\n usePSD,\n} from '../helpers/promise';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n Observable as IObservable,\n Subscription,\n} from '../public/types/observable';\nimport { Observable } from '../classes/observable/observable';\nimport { extendObservabilitySet } from './extend-observability-set';\nimport { rangesOverlap } from '../helpers/rangeset';\nimport { domDeps } from '../classes/dexie/dexie-dom-dependencies';\nimport { Transaction } from '../classes/transaction';\nimport { obsSetsOverlap } from './obs-sets-overlap';\n\nexport interface LiveQueryContext {\n subscr: ObservabilitySet;\n signal: AbortSignal;\n requery: () => void;\n trans: null | Transaction;\n querier: Function; // For debugging purposes and Error messages\n}\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx: LiveQueryContext) {\n const wasRootExec = beginMicroTickScope(); // Performance: Avoid starting a new microtick scope within the async context.\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n let rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n // Make sure to set rv = rv.finally in order to wait to after decrementExpectedAwaits() has been called.\n // This fixes zone leaking issue that the liveQuery zone can leak to observer's next microtask.\n rv = (rv as Promise).finally(decrementExpectedAwaits);\n }\n return rv;\n } finally {\n wasRootExec && endMicroTickScope(); // Given that we created the microtick scope, we must also end it.\n }\n }\n\n let closed = false;\n let abortController: AbortController;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n if (closed) return;\n closed = true;\n if (abortController) abortController.abort();\n if (startedListening) globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let startedListening = false;\n\n const doQuery = () => execInGlobalContext(_doQuery);\n\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const _doQuery = () => {\n if (\n closed || // closed - don't run!\n !domDeps.indexedDB) // SSR in sveltekit, nextjs etc\n {\n return;\n }\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n // Abort signal fill three purposes:\n // 1. Abort the query if the observable is unsubscribed.\n // 2. Abort the query if a new query is made before the previous one has completed.\n // 3. For cached queries to know if they should remain in memory or could be enqued for being freed up.\n // (they will remain in memory for a short time and if noone needs them again, they will eventually be freed up)\n if (abortController) abortController.abort(); // Cancel previous query. Last query will be cancelled on unsubscribe().\n abortController = new AbortController();\n \n const ctx: LiveQueryContext = {\n subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier,\n trans: null // Make the scope transactionless (don't reuse transaction from outer scope of the caller of subscribe())\n }\n const ret = execute(ctx);\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n // closed - no subscriber anymore.\n // signal.aborted - new query was made before this one completed and\n // the querier might have catched AbortError and return successful result.\n // If so, we should not rely in that result because we know we have aborted\n // this run, which means there's another run going on that will handle accumMuts\n // and we must not base currentObs on the half-baked subscr.\n return;\n }\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n if (!objectIsEmpty(currentObs) && !startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n }\n execInGlobalContext(()=>!closed && observer.next && observer.next(result));\n },\n (err) => {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err?.name)) {\n if (!closed) execInGlobalContext(()=>{\n if (closed) return;\n observer.error && observer.error(err);\n });\n }\n }\n );\n };\n\n // Use setTimeot here to guarantee execution in a private macro task before and\n // after. The helper executeInGlobalContext(_doQuery) is not enough here because\n // caller of `subscribe()` could be anything, such as a frontend framework that will\n // continue in the same tick after subscribe() is called and call other\n // eftects, that could involve dexie operations such as writing to the DB.\n // If that happens, the private zone echoes from a live query tast started here\n // could still be ongoing when the other operations start and make them inherit\n // the async context from a live query.\n setTimeout(doQuery, 0);\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\nimport { cache } from '../../live-query/cache/cache';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName, {addons: []});\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap,\n //maxKey: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: domDeps,\n cache,\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n // default: Dexie, // Commented because solved in index-umd.ts instead.\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n // Dexie: Dexie // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport { signalSubscribersNow } from './cache/signalSubscribers';\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\n/** Called from listeners to BroadcastChannel and DOM event to\n * propagate the event locally into dexie's storagemutated event\n * and invalidate cached queries.\n * \n * This function is only called when the event is not originating\n * from this same Dexie module - either from another redundant dexie import\n * or from a foreign tab or worker. That's why we need to invalidate\n * the cache when this happens.\n */\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n // Fire the \"storagemutated\" event.\n globalEvents.storagemutated.fire(updateParts);\n // Invalidate cached queries and signal subscribers to requery.\n signalSubscribersNow(updateParts, true);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nexport let bc: BroadcastChannel;\n\nexport let createBC = ()=>{};\n\nif (typeof BroadcastChannel !== 'undefined') {\n createBC = () => {\n bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n bc.onmessage = ev => ev.data && propagateLocally(ev.data);\n }\n createBC();\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n }\n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n}\n","import { Dexie } from \"./classes/dexie\";\nimport { connections } from \"./globals/constants\";\nimport { debug } from \"./helpers/debug\";\nimport { RangeSet } from \"./helpers/rangeset\";\nimport { bc, createBC } from \"./live-query/enable-broadcast\";\nimport { propagateLocally } from \"./live-query/propagate-locally\";\n\n\nif (typeof addEventListener !== 'undefined') {\n addEventListener('pagehide', (event) => {\n if (!Dexie.disableBfCache && event.persisted) {\n if (debug) console.debug('Dexie: handling persisted pagehide');\n bc?.close();\n for (const db of connections) {\n db.close({disableAutoOpen: false});\n }\n }\n });\n addEventListener('pageshow', (event) => {\n if (!Dexie.disableBfCache && event.persisted) {\n if (debug) console.debug('Dexie: handling persisted pageshow');\n createBC();\n propagateLocally({all: new RangeSet(-Infinity, [[]])}); // Trigger all queries to requery\n }\n });\n}\n","import { PropModification } from \"../../helpers/prop-modification\";\n\nexport function add(value: number | bigint | Array) {\n return new PropModification({add: value});\n}\n","import { PropModification } from \"../../helpers/prop-modification\";\n\nexport function remove(value: number | bigint | Array) {\n return new PropModification({remove: value});\n}\n","import { PropModification } from \"../../helpers/prop-modification\";\n\nexport function replacePrefix(a: string, b:string) {\n return new PropModification({replacePrefix: [a, b]});\n}\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport './support-bfcache';\nimport { liveQuery } from './live-query/live-query';\nimport { Entity } from './classes/entity/Entity';\nimport { cmp } from './functions/cmp';\nimport { PropModification, PropModSymbol } from './helpers/prop-modification';\nimport { replacePrefix, add, remove } from './functions/propmods';\n\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport { Entity };\nexport { cmp };\nexport { PropModSymbol, PropModification, replacePrefix, add, remove };\nexport default Dexie;\n","// Issue #1127. Need another index.ts for the UMD module with only a default export\n// like it was before.\n// In practice though, the UMD export will also export the named export in \n// https://github.com/dfahlander/Dexie.js/blob/c9187ae60c0d7a424f85bab3af179fbbc9901c8e/src/classes/dexie/dexie-static-props.ts#L223-L228\nimport Dexie from \"./index\";\nimport * as namedExports from \"./index\";\nimport { __assign } from 'tslib';\n__assign(Dexie, namedExports, {default: Dexie});\nexport default Dexie;\n"],"names":["asap","_a","Promise","Dexie","safari14Workaround","_Dexie","Debug.debug","Debug.setDebug"],"mappings":";;;;;;;;;;;;;;;;;;;IAAA;IACA;IAEA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAGA,IAAI,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,EAAE;IACnC,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;IACzC,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,KAAK,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;IACpF,QAAQ,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1G,IAAI,OAAO,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/B,CAAC,CAAC;IAEK,SAAS,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE;IAChC,IAAI,IAAI,OAAO,CAAC,KAAK,UAAU,IAAI,CAAC,KAAK,IAAI;IAC7C,QAAQ,MAAM,IAAI,SAAS,CAAC,sBAAsB,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,+BAA+B,CAAC,CAAC;IAClG,IAAI,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACxB,IAAI,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,EAAE;IAC3C,IAAI,CA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CAAC;QACH,gBAAgB,CAAC,UAAU,EAAE,UAAC,KAAK;YACjC,IAAI,CAACA,OAAK,CAAC,cAAc,IAAI,KAAK,CAAC,SAAS,EAAE;gBAC5C,IAAI,KAAK;oBAAE,OAAO,CAAC,KAAK,CAAC,oCAAoC,CAAC,CAAC;gBAC/D,QAAQ,EAAE,CAAC;gBACX,gBAAgB,CAAC,EAAC,GAAG,EAAE,IAAI,QAAQ,CAAC,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC,EAAC,CAAC,CAAC;aACxD;SACF,CAAC,CAAC;IACL;;aCvBgB,GAAG,CAAC,KAA+C;QACjE,OAAO,IAAI,gBAAgB,CAAC,EAAC,GAAG,EAAE,KAAK,EAAC,CAAC,CAAC;IAC5C;;aCFgB,MAAM,CAAC,KAA+C;QACpE,OAAO,IAAI,gBAAgB,CAAC,EAAC,MAAM,EAAE,KAAK,EAAC,CAAC,CAAC;IAC/C;;aCFgB,aAAa,CAAC,CAAS,EAAE,CAAQ;QAC/C,OAAO,IAAI,gBAAgB,CAAC,EAAC,aAAa,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAC,CAAC,CAAC;IACvD;;ICmBA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCI,YAAc,CAACD,KAAkC,CAAC;;;;;;;;;;;;;;;;;;;ICnBlD,QAAQ,CAACH,OAAK,EAAE,YAAY,EAAE,EAAC,OAAO,EAAEA,OAAK,EAAC,CAAC;;;;;;;;"}
\ No newline at end of file
diff --git a/grails-app/assets/vendor/dexiejs/dexie.min.js b/grails-app/assets/vendor/dexiejs/dexie.min.js
new file mode 100644
index 00000000..48114a40
--- /dev/null
+++ b/grails-app/assets/vendor/dexiejs/dexie.min.js
@@ -0,0 +1,2 @@
+(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Dexie=t()})(this,function(){"use strict";var s=function(e,t){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};var _=function(){return(_=Object.assign||function(e){for(var t,n=1,r=arguments.length;n.",Ze="String expected.",et=[],tt="__dbnames",nt="readonly",rt="readwrite";function it(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}var ot={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function at(t){return"string"!=typeof t||/\./.test(t)?function(e){return e}:function(e){return void 0===e[t]&&t in e&&delete(e=S(e))[t],e}}function ut(){throw Y.Type()}function st(e,t){try{var n=ct(e),r=ct(t);if(n!==r)return"Array"===n?1:"Array"===r?-1:"binary"===n?1:"binary"===r?-1:"string"===n?1:"string"===r?-1:"Date"===n?1:"Date"!==r?NaN:-1;switch(n){case"number":case"Date":case"string":return ts+c&&f(s+b)})})}var h=yt(r)&&r.limit===1/0&&("function"!=typeof w||w===Kt)&&{index:r.index,range:r.range};return f(0).then(function(){if(0=c})).length?(e.forEach(function(u){t.push(function(){var t=h,e=u._cfg.dbschema;fn(s,t,f),fn(s,e,f),h=s._dbSchema=e;var n=an(t,e);n.add.forEach(function(e){un(f,e[0],e[1].primKey,e[1].indexes)}),n.change.forEach(function(e){if(e.recreate)throw new Y.Upgrade("Not yet support for changing primary key");var t=f.objectStore(e.name);e.add.forEach(function(e){return cn(t,e)}),e.change.forEach(function(e){t.deleteIndex(e.name),cn(t,e)}),e.del.forEach(function(e){return t.deleteIndex(e)})});var r=u._cfg.contentUpgrade;if(r&&u._cfg.version>c){Zt(s,f),l._memoizedTables={};var i=g(e);n.del.forEach(function(e){i[e]=t[e]}),tn(s,[s.Transaction.prototype]),en(s,[s.Transaction.prototype],x(i),i),l.schema=i;var o,a=B(r);a&&Le();n=_e.follow(function(){var e;(o=r(l))&&a&&(e=Ue.bind(null,null),o.then(e,e))});return o&&"function"==typeof o.then?_e.resolve(o):n.then(function(){return o})}}),t.push(function(e){var t,n,r=u._cfg.dbschema;t=r,n=e,[].slice.call(n.db.objectStoreNames).forEach(function(e){return null==t[e]&&n.db.deleteObjectStore(e)}),tn(s,[s.Transaction.prototype]),en(s,[s.Transaction.prototype],s._storeNames,s._dbSchema),l.schema=s._dbSchema}),t.push(function(e){s.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(s.idbdb.version/10)===u._cfg.version?(s.idbdb.deleteObjectStore("$meta"),delete s._dbSchema.$meta,s._storeNames=s._storeNames.filter(function(e){return"$meta"!==e})):e.objectStore("$meta").put(u._cfg.version,"version"))})}),function e(){return t.length?_e.resolve(t.shift()(l.idbtrans)).then(e):_e.resolve()}().then(function(){sn(h,f)})):_e.resolve();var s,c,l,f,t,h}).catch(u)):(x(o).forEach(function(e){un(i,e,o[e].primKey,o[e].indexes)}),Zt(n,i),void _e.follow(function(){return n.on.populate.fire(a)}).catch(u));var e,t})}function on(e,r){sn(e._dbSchema,r),r.db.version%10!=0||r.objectStoreNames.contains("$meta")||r.db.createObjectStore("$meta").add(Math.ceil(r.db.version/10-1),"version");var t=ln(0,e.idbdb,r);fn(e,e._dbSchema,r);for(var n=0,i=an(t,e._dbSchema).change;nMath.pow(2,62)?0:e.oldVersion,m=e<1,f.idbdb=l.result,p&&on(f,v),rn(f,e/10,v,n))},n),l.onsuccess=qe(function(){v=null;var e,t,n,r,i,o=f.idbdb=l.result,a=b(o.objectStoreNames);if(0d.limit?t.length=d.limit:e.length===d.limit&&t.length=r.limit&&(!r.values||e.req.values)&&Xn(e.req.query.range,r.query.range)}),!1,i,o];case"count":a=o.find(function(e){return Gn(e.req.query.range,r.query.range)});return[a,!!a,i,o]}}(O,c,"query",t),a=o[0],e=o[1],u=o[2],s=o[3];return a&&e?a.obsSet=t.obsSet:(e=l.query(t).then(function(e){var t=e.result;if(a&&(a.res=t),i){for(var n=0,r=t.length;n