"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.split = void 0;
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/**
 * Receives observable that emits strings, and returns a new observable
 * that also returns strings separated by delimiter.
 *
 * Input stream:
 *
 *     asdf.f -> df..aaa. -> dfsdf
 *
 * Output stream, assuming "." is used as delimiter:
 *
 *     asdf -> fdf -> aaa -> dfsdf
 *
 */
const split = (delimiter = '\n') => in$ => {
  const out$ = new _rxjs.Subject();
  let startingText = '';
  in$.subscribe(chunk => {
    const messages = (startingText + chunk).split(delimiter);

    // We don't want to send the last message here, since it may or
    // may not be a partial message.
    messages.slice(0, -1).forEach(out$.next.bind(out$));
    startingText = messages.length ? messages[messages.length - 1] : '';
  }, out$.error.bind(out$), () => {
    out$.next(startingText);
    out$.complete();
  });
  return out$.pipe((0, _operators.filter)(Boolean));
};
exports.split = split;