'use strict';

const vm = require('vm'); const net = require('net'); const os = require('os'); const fs = require('fs'); let contexts = {}; let process_exit = false;

/*** circular-json, originally taken from raw.githubusercontent.com/WebReflection/circular-json/

Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

***

the original version has been restructured and modified to fit in here,
only stringify is used, unused parts removed.

*/

const CircularJSON = {}; CircularJSON.specialChar = '~'; CircularJSON.safeSpecialChar = '\x' + ('0' + CircularJSON.specialChar.charCodeAt(0).toString(16)).slice(-2); CircularJSON.escapedSafeSpecialChar = '\' + CircularJSON.safeSpecialChar; CircularJSON.specialCharRG = new RegExp(CircularJSON.safeSpecialChar, 'g'); CircularJSON.indexOf = [].indexOf || function(v){

  for(let i=this.length;i--&&this[i]!==v;);
  return i;
};

CircularJSON.generateReplacer = function (value, replacer, resolve) {

  let
      doNotIgnore = false,
      inspect = !!replacer,
      path = [],
      all  = [value],
      seen = [value],
      mapp = [resolve ? CircularJSON.specialChar : '[Circular]'],
      last = value,
      lvl  = 1,
      i, fn
  ;
  if (inspect) {
    fn = typeof replacer === 'object' ?
        function (key, value) {
          return key !== '' && CircularJSON.indexOf.call(replacer, key) < 0 ? void 0 : value;
        } :
        replacer;
  }
  return function(key, value) {
    // the replacer has rights to decide
    // if a new object should be returned
    // or if there's some key to drop
    // let's call it here rather than "too late"
    if (inspect) value = fn.call(this, key, value);
    // first pass should be ignored, since it's just the initial object
    if (doNotIgnore) {
      if (last !== this) {
        i = lvl - CircularJSON.indexOf.call(all, this) - 1;
        lvl -= i;
        all.splice(lvl, all.length);
        path.splice(lvl - 1, path.length);
        last = this;
      }
      // console.log(lvl, key, path);
      if (typeof value === 'object' && value) {
        // if object isn't referring to parent object, add to the
        // object path stack. Otherwise it is already there.
        if (CircularJSON.indexOf.call(all, value) < 0) {
          all.push(last = value);
        }
        lvl = all.length;
        i = CircularJSON.indexOf.call(seen, value);
        if (i < 0) {
          i = seen.push(value) - 1;
          if (resolve) {
            // key cannot contain specialChar but could be not a string
            path.push(('' + key).replace(CircularJSON.specialCharRG, CircularJSON.safeSpecialChar));
            mapp[i] = CircularJSON.specialChar + path.join(CircularJSON.specialChar);
          } else {
            mapp[i] = mapp[0];
          }
        } else {
          value = mapp[i];
        }
      } else {
        if (typeof value === 'string' && resolve) {
          // ensure no special char involved on deserialization
          // in this case only first char is important
          // no need to replace all value (better performance)
          value = value
              .replace(CircularJSON.safeSpecialChar, CircularJSON.escapedSafeSpecialChar)
              .replace(CircularJSON.specialChar, CircularJSON.safeSpecialChar);
        }
      }
    } else {
      doNotIgnore = true;
    }
    return value;
  };
};

CircularJSON.stringify = function stringify(value, replacer, space, doNotResolve) {

  return JSON.stringify(
      value,
      CircularJSON.generateReplacer(value, replacer, !doNotResolve),
      space
  );
};

/*** end of circular-json ***/

function attachFunctionSource(responder_path, context, func) {

return func + " = async function(...method_args) {\n\
  let context = \"" + context + "\";\n\
  let func = \"" + func +"\";\n\
  let request = [context, func, method_args];\n\
  let responder_path = '" + responder_path + "';\n\
  if (!global.__responder_socket) {\n\
    return new Promise(function(resolve, reject) {\n\
      setTimeout(function(){\n\
        if (os.platform().indexOf('win') > -1) {\n\
          let socket = net.connect(responder_path);\n\
          socket.on('connect', function(){\n\
            global.__responder_socket = true;\n\
            socket.destroy();\n\
            resolve(" + func + "(...method_args));\n\
          })\n\
          socket.on('error', function (err) {\n\
            resolve(" + func + "(...method_args));\n\
          });\n\
        } else {\n\
          if (fs.existsSync(responder_path)) { global.__responder_socket = true; }\n\
          resolve(" + func + "(...method_args));\n\
        }\n\
      }, 10)\n\
    });\n\
  }\n\
  return new Promise(function(resolve, reject) {\n\
    let request_json = JSON.stringify(request);\n\
    let buffer = Buffer.alloc(0);\n\
    let socket = net.connect(responder_path);\n\
    socket.setTimeout(2000);\n\
    socket.on('error', function (err) {\n\
        if (err.syscall === 'connect') {\n\
          // ignore, close will handle\n\
        } else if (os.platform().indexOf('win') > -1 && err.message.includes('read EPIPE')) {\n\
          // ignore, close will handle\n\
        } else if (os.platform().indexOf('win') > -1 && err.message.includes('write EPIPE')) {\n\
          // ignore, close will handle\n\
        } else { reject(err); }\n\
    });\n\
    socket.on('ready', function () {\n\
        socket.write(request_json + \"\x04\");\n\
    });\n\
    socket.on('data', function (data) {\n\
        buffer = Buffer.concat([buffer, data]);\n\
    });\n\
    socket.on('timeout', function() {\n\
        socket.destroy();\n\
        reject();\n\
    });\n\
    socket.on('close', function() {\n\
      if (buffer.length > 0) {\n\
          let method_result = JSON.parse(buffer.toString('utf8'));\n\
          if (method_result[0] == 'err') {\n\
            reject(method_result);\n\
          } else {\n\
            resolve(method_result[1]);\n\
          }\n\
      } else {\n\
        resolve(null);\n\
      }\n\
    });\n\
  });\n\
}\n";

}

function createCompatibleContext(uuid, options) {

let c = vm.createContext();
vm.runInContext('delete this.console', c, "(execjs)");
contexts[uuid] = { context: c, options: options };
return c;

}

function createPermissiveContext(uuid, options) {

let c = vm.createContext({ global: { __responder_socket: false }, process: { release: { name: "node" }, env: process.env }, Buffer, clearTimeout, fs, net, os, require, setTimeout });
contexts[uuid] = { context: c, options: options };
return c;

}

function formatResult(result) {

if (typeof result === 'undefined' && result !== null) { return ['ok']; }
else {
    try { return ['ok', result]; }
    catch (err) { return ['err', ['', err].join(''), err.stack]; }
}

}

function getContext(uuid) {

if (contexts[uuid]) { return contexts[uuid].context; }
else { return null; }

}

function getContextOptions(uuid) {

let options = { filename: "(execjs)", displayErrors: true };
if (contexts[uuid].options.timeout) {
  options.timeout = contexts[uuid].options.timeout;
}
return options;

}

function massageStackTrace(stack) {

if (stack && stack.indexOf("SyntaxError") == 0) {
    return "(execjs):1\n" + stack;
} else {
    return stack;
}

}

let socket_path = process.env.SOCKET_PATH; if (!socket_path) { throw 'No SOCKET_PATH given!'; };

let commands = {

attach: function(input) {
  let context = getContext(input.context);
  let responder_path;
  if (os.platform().indexOf('win') > -1) { responder_path = '\\\\\\\\.\\\\pipe\\\\' + socket_path + '_responder'; }
  else { responder_path = socket_path + '_responder' }
  let result = vm.runInContext(attachFunctionSource(responder_path, input.context, input.func), context, { filename: "(execjs)", displayErrors: true });
  return formatResult(result);
},
create: function (input) {
  let context = createCompatibleContext(input.context, input.options);
  let result = vm.runInContext(input.source, context, getContextOptions(input.context));
  return formatResult(result);
},
createp: function (input) {
  let context = createPermissiveContext(input.context, input.options);
  let result = vm.runInContext(input.source, context, getContextOptions(input.context));
  return formatResult(result);
},
deleteContext: function(uuid) {
    delete contexts[uuid];
    return [1];
},
exit: function(code) {
    process_exit = code;
    return ['ok'];
},
exec: function (input) {
    let result = vm.runInContext(input.source, getContext(input.context), getContextOptions(input.context));
    return formatResult(result);
},
eval: function (input) {
  if (input.source.match(/^\s*{/)) { input.source = "(" + input.source + ")"; }
  else if (input.source.match(/^\s*function\s*\(/)) { input.source = "(" + input.source + ")"; }
  let result = vm.runInContext(input.source, getContext(input.context), getContextOptions(input.context));
  return formatResult(result);
},
// ctxo: function (input) {
//   return formatResult(getContextOptions(input.context));
// },

};

let server = net.createServer(function(s) {

let received_data = [];
s.on('data', function (data) {
    received_data.push(data);
    if (data[data.length - 1] !== 4) { return; }
    let request = received_data.join('').toString('utf8');
    request = request.substr(0, request.length - 1);
    received_data = [];
    let input, result;
    let outputJSON = '';
    try { input = JSON.parse(request); }
    catch(err) { 
      outputJSON = JSON.stringify(['err', ['', err].join(''), err.stack]);
      s.write([outputJSON, "\x04"].join(''));
      return;
    }
    try { result = commands[input.cmd].apply(null, input.args); } 
    catch (err) { 
      outputJSON = JSON.stringify(['err', ['', err].join(''), massageStackTrace(err.stack)]);
      s.write([outputJSON, "\x04"].join(''));
      return;
    }
    try { outputJSON = JSON.stringify(result); }
    catch(err) {
        if (err.message.includes('circular')) { outputJSON = CircularJSON.stringify(result); }
        else { outputJSON = JSON.stringify([['', err].join(''), err.stack]); }
        s.write([outputJSON, "\x04"].join(''));
        if (process_exit !== false) { process.exit(process_exit); }
        return;
    }
    try { s.write([outputJSON, "\x04"].join('')); }
    catch (err) {}
    if (process_exit !== false) { process.exit(process_exit); }
});

});

if (os.platform().indexOf('win') > -1) { server.listen('\\.\pipe\' + socket_path); } else { server.listen(socket_path); }