"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (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));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndexLevel = void 0;
var object_js_1 = require("../utils/object.js");
var level_wrapper_js_1 = require("./level-wrapper.js");
/**
 * A LevelDB implementation for indexing the messages stored in the DWN.
 */
var IndexLevel = /** @class */ (function () {
    function IndexLevel(config) {
        this.config = __assign({ createLevelDatabase: level_wrapper_js_1.createLevelDatabase }, config);
        this.db = new level_wrapper_js_1.LevelWrapper(__assign(__assign({}, this.config), { valueEncoding: 'utf8' }));
    }
    IndexLevel.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.open()];
            });
        });
    };
    IndexLevel.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.close()];
            });
        });
    };
    /**
     * Adds indexes for a specific data/object/content.
     * @param dataId ID of the data/object/content being indexed.
     */
    IndexLevel.prototype.put = function (dataId, indexes, options) {
        return __awaiter(this, void 0, void 0, function () {
            var operations, propertyName, propertyValue, key;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        indexes = (0, object_js_1.flatten)(indexes);
                        operations = [];
                        // create an index entry for each property in the `indexes`
                        for (propertyName in indexes) {
                            propertyValue = indexes[propertyName];
                            key = this.join(propertyName, this.encodeValue(propertyValue), dataId);
                            operations.push({ type: 'put', key: key, value: dataId });
                        }
                        // create a reverse lookup entry for data ID -> its indexes
                        // this is for indexes deletion (`delete()`): so that given the data ID, we are able to delete all its indexes
                        // we can consider putting this info in a different data partition if this ever becomes more complex/confusing
                        operations.push({ type: 'put', key: "__".concat(dataId, "__indexes"), value: JSON.stringify(indexes) });
                        return [4 /*yield*/, this.db.batch(operations, options)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    IndexLevel.prototype.query = function (filter, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var propertyNameToPromises, propertyName, propertyFilter, _b, _c, propertyValue, exactMatchesPromise, rangeMatchesPromise, exactMatchesPromise, missingPropertyMatchesForId, matchedIDs, _d, _e, _f, propertyName, promises, promises_1, promises_1_1, promise, _g, _h, dataId, e_1_1, e_2_1, e_3_1;
            var e_4, _j, e_3, _k, e_2, _l, e_1, _m;
            return __generator(this, function (_o) {
                switch (_o.label) {
                    case 0:
                        propertyNameToPromises = {};
                        // Do a separate DB query for each property in `filter`
                        // We will find the union of these many individual queries later.
                        for (propertyName in filter) {
                            propertyFilter = filter[propertyName];
                            if (typeof propertyFilter === 'object') {
                                if (Array.isArray(propertyFilter)) {
                                    // `propertyFilter` is a AnyOfFilter
                                    // Support OR matches by querying for each values separately,
                                    // then adding them to the promises associated with `propertyName`
                                    propertyNameToPromises[propertyName] = [];
                                    try {
                                        for (_b = (e_4 = void 0, __values(new Set(propertyFilter))), _c = _b.next(); !_c.done; _c = _b.next()) {
                                            propertyValue = _c.value;
                                            exactMatchesPromise = this.findExactMatches(propertyName, propertyValue, options);
                                            propertyNameToPromises[propertyName].push(exactMatchesPromise);
                                        }
                                    }
                                    catch (e_4_1) { e_4 = { error: e_4_1 }; }
                                    finally {
                                        try {
                                            if (_c && !_c.done && (_j = _b.return)) _j.call(_b);
                                        }
                                        finally { if (e_4) throw e_4.error; }
                                    }
                                }
                                else {
                                    rangeMatchesPromise = this.findRangeMatches(propertyName, propertyFilter, options);
                                    propertyNameToPromises[propertyName] = [rangeMatchesPromise];
                                }
                            }
                            else {
                                exactMatchesPromise = this.findExactMatches(propertyName, propertyFilter, options);
                                propertyNameToPromises[propertyName] = [exactMatchesPromise];
                            }
                        }
                        missingPropertyMatchesForId = {};
                        matchedIDs = [];
                        _o.label = 1;
                    case 1:
                        _o.trys.push([1, 18, 19, 20]);
                        _d = __values(Object.entries(propertyNameToPromises)), _e = _d.next();
                        _o.label = 2;
                    case 2:
                        if (!!_e.done) return [3 /*break*/, 17];
                        _f = __read(_e.value, 2), propertyName = _f[0], promises = _f[1];
                        _o.label = 3;
                    case 3:
                        _o.trys.push([3, 14, 15, 16]);
                        promises_1 = (e_2 = void 0, __values(promises)), promises_1_1 = promises_1.next();
                        _o.label = 4;
                    case 4:
                        if (!!promises_1_1.done) return [3 /*break*/, 13];
                        promise = promises_1_1.value;
                        _o.label = 5;
                    case 5:
                        _o.trys.push([5, 10, 11, 12]);
                        e_1 = void 0;
                        return [4 /*yield*/, promise];
                    case 6:
                        _g = (__values.apply(void 0, [_o.sent()])), _h = _g.next();
                        _o.label = 7;
                    case 7:
                        if (!!_h.done) return [3 /*break*/, 9];
                        dataId = _h.value;
                        // if first time seeing a property matching for the data/object, record all properties needing a match to track progress
                        (_a = missingPropertyMatchesForId[dataId]) !== null && _a !== void 0 ? _a : (missingPropertyMatchesForId[dataId] = new Set(__spreadArray([], __read(Object.keys(filter)), false)));
                        missingPropertyMatchesForId[dataId].delete(propertyName);
                        if (missingPropertyMatchesForId[dataId].size === 0) {
                            // full filter match, add it to return list
                            matchedIDs.push(dataId);
                        }
                        _o.label = 8;
                    case 8:
                        _h = _g.next();
                        return [3 /*break*/, 7];
                    case 9: return [3 /*break*/, 12];
                    case 10:
                        e_1_1 = _o.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 12];
                    case 11:
                        try {
                            if (_h && !_h.done && (_m = _g.return)) _m.call(_g);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7 /*endfinally*/];
                    case 12:
                        promises_1_1 = promises_1.next();
                        return [3 /*break*/, 4];
                    case 13: return [3 /*break*/, 16];
                    case 14:
                        e_2_1 = _o.sent();
                        e_2 = { error: e_2_1 };
                        return [3 /*break*/, 16];
                    case 15:
                        try {
                            if (promises_1_1 && !promises_1_1.done && (_l = promises_1.return)) _l.call(promises_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                        return [7 /*endfinally*/];
                    case 16:
                        _e = _d.next();
                        return [3 /*break*/, 2];
                    case 17: return [3 /*break*/, 20];
                    case 18:
                        e_3_1 = _o.sent();
                        e_3 = { error: e_3_1 };
                        return [3 /*break*/, 20];
                    case 19:
                        try {
                            if (_e && !_e.done && (_k = _d.return)) _k.call(_d);
                        }
                        finally { if (e_3) throw e_3.error; }
                        return [7 /*endfinally*/];
                    case 20: return [2 /*return*/, matchedIDs];
                }
            });
        });
    };
    IndexLevel.prototype.delete = function (dataId, options) {
        return __awaiter(this, void 0, void 0, function () {
            var serializedIndexes, indexes, ops, propertyName, propertyValue, key;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.db.get("__".concat(dataId, "__indexes"), options)];
                    case 1:
                        serializedIndexes = _a.sent();
                        if (!serializedIndexes) {
                            return [2 /*return*/];
                        }
                        indexes = JSON.parse(serializedIndexes);
                        ops = [];
                        for (propertyName in indexes) {
                            propertyValue = indexes[propertyName];
                            key = this.join(propertyName, this.encodeValue(propertyValue), dataId);
                            ops.push({ type: 'del', key: key });
                        }
                        ops.push({ type: 'del', key: "__".concat(dataId, "__indexes") });
                        return [4 /*yield*/, this.db.batch(ops, options)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    IndexLevel.prototype.clear = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.db.clear()];
            });
        });
    };
    /**
     * @returns IDs of data that matches the exact property and value.
     */
    IndexLevel.prototype.findExactMatches = function (propertyName, propertyValue, options) {
        var e_5, _a;
        return __awaiter(this, void 0, void 0, function () {
            var propertyValuePrefix, iteratorOptions, matches, _b, _c, _d, key, dataId, e_5_1;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        propertyValuePrefix = this.join(propertyName, this.encodeValue(propertyValue));
                        iteratorOptions = {
                            gt: propertyValuePrefix
                        };
                        matches = [];
                        _e.label = 1;
                    case 1:
                        _e.trys.push([1, 6, 7, 12]);
                        _b = __asyncValues(this.db.iterator(iteratorOptions, options));
                        _e.label = 2;
                    case 2: return [4 /*yield*/, _b.next()];
                    case 3:
                        if (!(_c = _e.sent(), !_c.done)) return [3 /*break*/, 5];
                        _d = __read(_c.value, 2), key = _d[0], dataId = _d[1];
                        if (!key.startsWith(propertyValuePrefix)) {
                            return [3 /*break*/, 5];
                        }
                        matches.push(dataId);
                        _e.label = 4;
                    case 4: return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 12];
                    case 6:
                        e_5_1 = _e.sent();
                        e_5 = { error: e_5_1 };
                        return [3 /*break*/, 12];
                    case 7:
                        _e.trys.push([7, , 10, 11]);
                        if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
                        return [4 /*yield*/, _a.call(_b)];
                    case 8:
                        _e.sent();
                        _e.label = 9;
                    case 9: return [3 /*break*/, 11];
                    case 10:
                        if (e_5) throw e_5.error;
                        return [7 /*endfinally*/];
                    case 11: return [7 /*endfinally*/];
                    case 12: return [2 /*return*/, matches];
                }
            });
        });
    };
    /**
     * @returns IDs of data that matches the range filter.
     */
    IndexLevel.prototype.findRangeMatches = function (propertyName, rangeFilter, options) {
        var e_6, _a;
        return __awaiter(this, void 0, void 0, function () {
            var iteratorOptions, comparator, comparatorName, matches, _b, _c, _d, key, dataId, e_6_1, _e, _f, dataId, e_7_1;
            var e_7, _g;
            return __generator(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        iteratorOptions = {};
                        for (comparator in rangeFilter) {
                            comparatorName = comparator;
                            iteratorOptions[comparatorName] = this.join(propertyName, this.encodeValue(rangeFilter[comparatorName]));
                        }
                        // if there is no lower bound specified (`gt` or `gte`), we need to iterate from the upper bound,
                        // so that we will iterate over all the matches before hitting mismatches.
                        if (iteratorOptions.gt === undefined && iteratorOptions.gte === undefined) {
                            iteratorOptions.reverse = true;
                        }
                        matches = [];
                        _h.label = 1;
                    case 1:
                        _h.trys.push([1, 6, 7, 12]);
                        _b = __asyncValues(this.db.iterator(iteratorOptions, options));
                        _h.label = 2;
                    case 2: return [4 /*yield*/, _b.next()];
                    case 3:
                        if (!(_c = _h.sent(), !_c.done)) return [3 /*break*/, 5];
                        _d = __read(_c.value, 2), key = _d[0], dataId = _d[1];
                        // immediately stop if we arrive at an index entry for a different property
                        if (!key.startsWith(propertyName)) {
                            return [3 /*break*/, 5];
                        }
                        matches.push(dataId);
                        _h.label = 4;
                    case 4: return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 12];
                    case 6:
                        e_6_1 = _h.sent();
                        e_6 = { error: e_6_1 };
                        return [3 /*break*/, 12];
                    case 7:
                        _h.trys.push([7, , 10, 11]);
                        if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 9];
                        return [4 /*yield*/, _a.call(_b)];
                    case 8:
                        _h.sent();
                        _h.label = 9;
                    case 9: return [3 /*break*/, 11];
                    case 10:
                        if (e_6) throw e_6.error;
                        return [7 /*endfinally*/];
                    case 11: return [7 /*endfinally*/];
                    case 12:
                        if (!('lte' in rangeFilter)) return [3 /*break*/, 20];
                        _h.label = 13;
                    case 13:
                        _h.trys.push([13, 18, 19, 20]);
                        return [4 /*yield*/, this.findExactMatches(propertyName, rangeFilter.lte, options)];
                    case 14:
                        _e = __values.apply(void 0, [_h.sent()]), _f = _e.next();
                        _h.label = 15;
                    case 15:
                        if (!!_f.done) return [3 /*break*/, 17];
                        dataId = _f.value;
                        matches.push(dataId);
                        _h.label = 16;
                    case 16:
                        _f = _e.next();
                        return [3 /*break*/, 15];
                    case 17: return [3 /*break*/, 20];
                    case 18:
                        e_7_1 = _h.sent();
                        e_7 = { error: e_7_1 };
                        return [3 /*break*/, 20];
                    case 19:
                        try {
                            if (_f && !_f.done && (_g = _e.return)) _g.call(_e);
                        }
                        finally { if (e_7) throw e_7.error; }
                        return [7 /*endfinally*/];
                    case 20: return [2 /*return*/, matches];
                }
            });
        });
    };
    IndexLevel.prototype.encodeValue = function (value) {
        if (typeof value === 'string') {
            // We can't just `JSON.stringify` as that'll affect the sort order of strings.
            // For example, `'\x00'` becomes `'\\u0000'`.
            return "\"".concat(value, "\"");
        }
        return String(value);
    };
    /**
     * Joins the given values using the `\x00` (\u0000) character.
     */
    IndexLevel.prototype.join = function () {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return values.join("\0");
    };
    IndexLevel.prototype.dump = function () {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        console.group('db');
                        return [4 /*yield*/, ((_b = (_a = this.db)['dump']) === null || _b === void 0 ? void 0 : _b.call(_a))];
                    case 1:
                        _c.sent();
                        console.groupEnd();
                        return [2 /*return*/];
                }
            });
        });
    };
    return IndexLevel;
}());
exports.IndexLevel = IndexLevel;
//# sourceMappingURL=index-level.js.map