Coder Social home page Coder Social logo

metavm's Introduction

Metarhia script loader, node.js vm wrapper

ci status snyk npm version npm downloads/month npm downloads license

Create script from string

Script contains object expression. You can use it for configs, network packets, serialization format, etc.

const metavm = require('metavm');

const src = `({ field: 'value' });`;
const ms = metavm.createScript('Example', src);
console.log(ms);

Output:

MetaScript {
  name: 'Example',
  script: Script {},
  context: {},
  exports: { field: 'value' }
}

Script contains function expression. You can use it for api endpoints, domain logic stored in files or database, etc.

const metavm = require('metavm');

const src = `(a, b) => a + b;`;
const ms = metavm.createScript('Example', src);
console.log(ms);

Output:

MetaScript {
  name: 'Example',
  script: Script {},
  context: {},
  exports: [Function]
}

Read script from file

const metavm = require('.');

(async () => {
  const ms = await metavm.readScript('./test/examples/simple.js');
  console.log(ms);
})();

Output:

MetaScript {
  name: 'simple',
  script: Script {},
  context: {},
  exports: { field: 'value', add: [Function: add], sub: [Function: sub] }
}

License & Contributors

Copyright (c) 2020-2023 Metarhia contributors. Metavm is MIT licensed.
Metavm is a part of Metarhia technology stack.

metavm's People

Contributors

aliusdiemorietur avatar dependabot[bot] avatar shatanov avatar tshemsedinov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

metavm's Issues

Support CommonJS modules contract

  • Export with module.exports and exports
  • Implement module: Module interface
  • Support __filename and __dirname
  • Implement require interface

Execute require inside MetaScript context

Now if we load module inside MetaScript and pass require to it's context so module can load another module, this require will be executed in the global context of all application, not in internal MetaScript context. We need special require implementation to be executed inside MetaScript context.

Combine metarequire and createScript into a single call

Describe the solution you'd like
Now we call metarequire and then createScript passing same things into both. What we can do is to hide metarequire for external user and call it from createScript to hide complexity from external user.

Remove null scenario and return empty file Error instead

Тут читается src из файла и если !src возвращается null. Это срабатывает только на пустом файле.

if (!src) return null;

Тут в impress читаются изменения файлов в lib и domain и в логи прилетает ошибка
https://github.com/metarhia/impress/blob/fd1d8b320838ae86e020b0010f145e109314ffdf/lib/modules.js#L69

00:09:44  W1   error   TypeError: Cannot read property 'exports' of null
  Modules.change (/node_modules/impress/lib/modules.js:65:28)

Пустой файл подразумевается как ошибка, поэтому на мой взгляд логично выдавать на этот случай ошибку, что файл пуст, а не ошибку, которая отсылает к библиотекам метрахии. Такое возникает только при работе с прикладным кодом.
При работе с api (interfaces в импрессе) ошибка возникает только если добавить пустой файл в папку api. Если положить в папку внутри папки api ошибка не выводится. Видимо загрузка вложенных папок и файлов в них в api отличается от domain и lib.

Default context

Pass some identifiers from global context to createContext by default

Fix 1 line shift in stack traces

For example:

14:05:18  W2   error   127.0.0.1	POST	/api	500	
500 TypeError: Cannot destructure property 'token' of 'session' as it is undefined.
  method (/application/api/example.1/getClientInfo.js:7:13)
  Procedure.invoke (/node_modules/impress/lib/procedure.js:76:22)
  HttpChannel.rpc (/node_modules/metacom/lib/channel.js:247:27)
  processTicksAndRejections (internal/process/task_queues.js:95:5)

while getClientInfo.js have destructuring at line 6

({
  access: 'public',
  method: async () => {
    const { uuid, session, client } = context;
    const { ip } = client;
    const { token, accountId } = session;
    return { result: { ip, token, accountId, uuid } };
  },
});

Sandbox permissions

We need to control following

  • Access to node internal modules
  • Access npm modules
  • Access modules to be loaded from disk
  • Substitute all mentioned modules in runtime
  • Cache loaded modules in memory
  • Wrap modules to separate objects in different sandboxes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.