"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.preload = exports.dispatchToShell = void 0;

var _debug = _interopRequireDefault(require("debug"));

var _core = require("@kui-shell/core");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/*
 * Copyright 2018-19 IBM Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __awaiter = void 0 && (void 0).__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());
  });
};

const debug = (0, _debug.default)('plugins/bash-like/cmds/catchall');
/**
 * Command handler that dispatches to an outer shell
 *
 */

const dispatchToShell = ({
  tab,
  command,
  argvNoOptions,
  execOptions,
  parsedOptions,
  createOutputStream
}) => __awaiter(void 0, void 0, void 0, function* () {
  /** trim the first part of "/bin/sh: someNonExistentCommand: command not found" */
  const cleanUpError = err => {
    if (err.message && typeof err.message === 'string') {
      throw new Error(err.message.replace(/[a-zA-Z0-9/]+:\s*/, '').trim());
    } else {
      throw err;
    }
  };

  const useRaw = (execOptions.raw || execOptions.type === _core.ExecType.Nested) && execOptions.quiet === undefined && execOptions.echo === undefined && execOptions.replSilence === undefined;
  const eOptions = useRaw || execOptions.isProxied ? execOptions : Object.assign({}, {
    stdout: yield createOutputStream()
  }, execOptions);
  const actualCommand = command.replace(/^(!|sendtopty)\s+/, '');

  if ((0, _core.isHeadless)() || !(0, _core.inBrowser)() && useRaw) {
    const {
      doExec
    } = yield Promise.resolve().then(() => require('./bash-like'));
    const response = yield doExec(actualCommand, eOptions).catch(cleanUpError);

    if (useRaw && (typeof response === 'number' || typeof response === 'boolean')) {
      return response;
    } else if (useRaw && typeof response === 'string') {
      try {
        return JSON.parse(response);
      } catch (err) {// debug('response maybe is not JSON', response)
      }
    }

    return response;
  } else {
    const {
      doExec
    } = yield Promise.resolve().then(() => require('../../pty/client'));

    const exec = () => doExec(tab, actualCommand, argvNoOptions, parsedOptions, eOptions);

    if (useRaw) {
      eOptions.quiet = true;
      eOptions.echo = false;
      eOptions.replSilence = true;
      let response = '';

      eOptions.onInit = () => _ => {
        if (typeof _ === 'string') {
          response += _;
        }
      };

      return exec().then(() => response).catch(cleanUpError);
    }

    return exec().catch(cleanUpError);
  }
});
/**
 * On preload, register the catchall handler
 *
 */


exports.dispatchToShell = dispatchToShell;

const preload = commandTree => {
  if ((0, _core.inBrowser)() && !(0, _core.hasProxy)()) {
    debug('skipping catchall registration: in browser and no remote proxy to support it');
    return;
  } //
  // if we aren't running in a browser, then pass any command not
  // found exceptions to the outer shell
  //


  return commandTree.catchall(() => true, // we will accept anything
  dispatchToShell, // command handler dispatches to outer shell
  0 // priority
  );
};

exports.preload = preload;