text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.Aligner = void 0;
  
  var _mendoza = require("mendoza");
  
  function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
  
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
  
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  
  function emptyVersionState(id) {
    return {
      id,
      hasAttrs: false,
      attrs: null,
      rev: null,
      events: [],
      aligned: false
    };
  }
  
  function align(history, state) {
    var idx = state.events.findIndex(evt => history.id === evt.transactionId);
  
    if (idx >= 0) {
      // Return the next event as we don't want this to be included.
      return idx + 1;
    }
  
    if (state.rev) {
      return state.rev === history.id ? 0 : -1;
    } // At this point the document doesn't exist and we were not able to match
    // it up with a received mutation. This is a bit unfortunate as we don't
    // have a _reliably_ way of aligning it. For now we just always assume
    // that it's consistent.
  
  
    return 0;
  }
  
  function startFromSnapshot(state, doc) {
    state.hasAttrs = true;
  
    if (doc) {
      state.attrs = _objectSpread({}, doc);
      if (typeof state.attrs._rev != 'string') throw new Error('snapshot has no _rev');
      state.rev = state.attrs._rev;
      delete state.attrs._rev;
    } else {
      state.attrs = null;
      state.rev = null;
    }
  
    state.events = [];
  }
  /**
   * The timeline consists of data from (1) the history, (2) live draft mutations, and
   * (3) live published mutations. It's critical for us that the chain of transactions
   * is complete and without holes. The following class can be used as a layer in front
   * of Timeline to ensure this:
   *
   * - Invoke `appendRemoteSnapshotEvent` when there's an incoming remote mutation.
   *   These mutations are buffered internally and _not_ passed to the timeline quite yet.
   *
   * - Once we've received snapshots for both draft and published, then `acceptsHistory`
   *   becomes true and the caller can fetch a chunk of the translog. The flag
   *   `earliestTransactionId` can be used to figure out where to fetch transactions from.
   *
   * - The caller invokes `prependHistoryEvent` for each of the events. These history events
   *   are always pushed to the timeline and it will become available immediately.
   *
   * - Internally this class will then try to align the history event to the received
   *   mutations and then dispatch to the timeline.
   *
   * - The aligner also maintains the latest version for both the draft and the published version.
   *
   *
   */
  
  
  class Aligner {
    constructor(timeline) {
      _defineProperty(this, "timeline", void 0);
  
      _defineProperty(this, "earliestTransactionId", null);
  
      _defineProperty(this, "_states", void 0);
  
      this.timeline = timeline;
      this._states = {
        draft: emptyVersionState(timeline.draftId),
        published: emptyVersionState(timeline.publishedId)
      };
    }
  
    appendRemoteSnapshotEvent(evt) {
      var state = this._states[evt.version];
  
      if (evt.type === 'snapshot') {
        this._maybeInvalidateHistory();
  
        startFromSnapshot(state, evt.document);
        return;
      }
  
      if (evt.type === 'remoteMutation') {
        if (state.aligned) {
          this._apply(state, evt);
  
          this.timeline.addRemoteMutation(evt);
        } else if (state.hasAttrs) {
          state.events.push(evt);
        } else {
          startFromSnapshot(state, evt.head);
        }
      }
    }
  
    prependHistoryEvent(evt) {
      if (!this.acceptsHistory) throw new Error('cannot prepend history at this point');
  
      for (var _i = 0, _Object$values = Object.values(this._states); _i < _Object$values.length; _i++) {
        var state = _Object$values[_i];
  
        if (!state.aligned) {
          var idx = align(evt, state);
  
          if (idx >= 0) {
            this._alignAtIndex(state, idx);
          }
        }
      }
  
      this.timeline.addTranslogEntry(evt);
      this.earliestTransactionId = evt.id;
    }
  
    didReachEarliestEntry() {
      for (var _i2 = 0, _Object$values2 = Object.values(this._states); _i2 < _Object$values2.length; _i2++) {
        var state = _Object$values2[_i2];
  
        if (!state.aligned) {
          if (state.attrs !== null) throw new Error('unable to find translog entry to align to');
  
          this._alignAtIndex(state, 0);
        }
      }
  
      this.timeline.didReachEarliestEntry();
    }
  
    get isAligned() {
      return Object.values(this._states).every(state => state.aligned);
    }
  
    get acceptsHistory() {
      return this._isComplete;
    }
  
    get currentDocument() {
      return {
        draft: this._states.draft.attrs,
        published: this._states.published.attrs
      };
    }
  
    _alignAtIndex(state, idx) {
      // These we must only apply locally since they are present in the fetched translog.
      var _iterator = _createForOfIteratorHelper(state.events.slice(0, idx)),
          _step;
  
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var mutEvt = _step.value;
  
          this._apply(state, mutEvt);
        } // ... while these must also be pushed to the timeline:
  
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
  
      var _iterator2 = _createForOfIteratorHelper(state.events.slice(idx)),
          _step2;
  
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var _mutEvt = _step2.value;
  
          this._apply(state, _mutEvt);
  
          this.timeline.addRemoteMutation(_mutEvt);
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
  
      state.events = [];
      state.aligned = true;
    }
  
    get _isComplete() {
      return Object.values(this._states).every(state => state.hasAttrs);
    } // eslint-disable-next-line class-methods-use-this
  
  
    _apply(state, evt) {
      state.attrs = (0, _mendoza.applyPatch)(state.attrs, evt.effects.apply);
      state.rev = evt.transactionId;
    }
  
    _maybeInvalidateHistory() {
      if (this._isComplete) {
        for (var _i3 = 0, _Object$values3 = Object.values(this._states); _i3 < _Object$values3.length; _i3++) {
          var state = _Object$values3[_i3];
          state.aligned = false;
        }
  
        this.earliestTransactionId = null;
        this.timeline.reset();
      }
    }
  
  }
  
  exports.Aligner = Aligner;