quick.js based sandbox

Overview

About

quick.js based sandbox

npm install define-function

works in any WebAssembly environment

  • node
  • browser
  • wechat miniprogram

Usage

define a function dynamically with javascript source code

const def = require('define-function')
const f = await def(`
    return 'hello';
`)
f() // 'hello'

function can have argument

const def = require('define-function')
const f = await def(`
    const [hello, world] = arguments;
    return hello + ' ' + world;
`)
f('hello', 'world') // 'hello world'

argument can be function

const def = require('define-function')
const f = await def(`
    const [print] = arguments;
    print('hello')
`)
f((msg) => {
    console.log(msg)
}) // 'hello'

argument can be async function

const def = require('define-function')
const f = await def(`
    const [print, sleep] = arguments;
    (async() => {
        print('hello')
        await sleep(1000);
        print('world')
    })();
`)
f(
    msg => console.log(msg),
    milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
) 
// hello
// world

can return promise back to host

const def = require('define-function')
const f = await def(`
    const [print, sleep] = arguments;
    return (async() => {
        print('hello')
        await sleep(1000);
        print('world')
    })();
`)
await f(
    msg => console.log(msg),
    milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))
)
console.log('done')
// hello
// world
// done

share context between multiple invocations

const { context } = require('define-function')
const ctx = context()
const f = await ctx.def(`
    global.counter = (global.counter || 0)+1;
    return counter; // counter can be referenced globally
`)
f() // 1
f() // 2
f() // 3
ctx.dispose()

inject value and callbacks into global

const { context } = require('define-function')
const ctx = context({ global: { 
    console,
    anwerOfEverything() {
        return 42;
    }
} }) // inject console and anwerOfEverything to global
const f = await ctx.def(`
    console.log(anwerOfEverything());
`)
f() // 42
ctx.dispose();

import and export es module

const { context } = require('define-function')
const ctx = context({ 
    loadModuleContent(moduleName) {
        if (moduleName !== 'xxx') {
            throw new Error('expect xxx');
        }
        return `export function sayHello() { return 'hello' }`
    }
});
const { hello } = await ctx.load(`
    import { sayHello } from 'xxx';
    export const hello = sayHello();
`)
console.log(hello) // hello
ctx.dispose();

Limit

  • function argument does not support Set/Map/Class or anything that can not survive JSON.parse(JSON.stringify), except the argument is a function
  • function return value does not support Set/Map/Class or anything that can not survive JSON.parse(JSON.stringify), except promise object
  • JSON.stringify and JSON.parse takes time, so the arguments and return value should be as small as possible for best performance

Similar projects

define-function has a simpler API and support async/await

You might also like...

Simple & Quick Access Addon For Home Assistant

Simple & Quick Access Addon For Home Assistant

Home Assistant - Firefox Addon Quick Access Home Assistant - Firefox Addon Usage Create a Custom Dashboard With Quick Access Entity In Home Assistant

Dec 25, 2022

Simple & Quick Access Addon For Homer Dashboard

Simple & Quick Access Addon For Homer Dashboard

Homer Dashboard - Firefox Addon Quick Access Homer Dashboard - Firefox Addon Usage Install Addon [ Firefox ] Configure The Addon Add The Quick Access

Jan 22, 2022

A quick way of bootstrapping a new mono-repo for a Web Application

A quick way of bootstrapping a new mono-repo for a Web Application

marp theme class author true gaia lead invert Matteo ronchi [email protected] Mono-repo Starter https://github.com/cef62/monorepo-template What

Jul 29, 2022

Quick One Liners in JavaScript, TypeScript, Python, Rust, Java, Ruby, C, C++

ONE LINERS This repository contains cool and simple one line utility functions to easily use common repetitive methods in JavaScript, TypeScript, Pyth

Mar 2, 2022

Quick access to view the current time and date in Ethiopian calendar.

Ethiopian-Current-time-chrome-extension Quick access to view the current time and date in Ethiopian calendar. steps to follow:- Extract the zip folder

Aug 26, 2022

Quick programmatically install npm dependencies 📦

qpind Install dependecies quick & programmatically 📦 Install # Using npm: npm install qpind # Using pnpm: pnpm add qpind # Using yarn: yarn add qpind

Oct 6, 2022

Easily open daily notes and periodic notes in new pane; customize periodic notes background; quick append new line to daily notes.

Easily open daily notes and periodic notes in new pane; customize periodic notes background; quick append new line to daily notes.

Obsidian daily notes opener This plugin adds a command for opening daily notes in a new pane (so that a keyboard shortcut could be used!) and gives ex

Dec 26, 2022

Quick and easy spring animation. Works with other animation libraries (gsap, animejs, framer motion, motion one, @okikio/animate, etc...) or the Web Animation API (WAAPI).

Quick and easy spring animation. Works with other animation libraries (gsap, animejs, framer motion, motion one, @okikio/animate, etc...)  or the Web Animation API (WAAPI).

spring-easing NPM | Github | Docs | Licence Quick and easy spring animations. Works with other animation libraries (gsap, animejs, @okikio/animate, mo

Dec 14, 2022

🎯 Wallet Lite is a Quick and Simple way to use your Tokens of Lunes Blockchain in a light Chrome extension

Lunes Wallet Lite Offered by: Lunes Installing Web store: Lunes Lite will be available on Chrome Web Store Build: Requisites NodeJS (16 or higher) Git

Oct 25, 2022
Comments
  • can not support class

    can not support class

    const { context } = require('define-function')
    
    ;(async () => {
      const ctx = context({
        global: {
          console,
          setTimeout,
          Promise,
        }
      })
      const f = await ctx.def(`
        const sleep = ms => new Promise(r => setTimeout(() => r(), ms));
        sleep(2000).then(() => console.log('2000'))
      `)
      f() 
    })()
    

    Expect this can run correctly.

    opened by bibidu 2
Owner
Tao Wen
function is all u need
Tao Wen
Remix sandbox repo for Rust compiled to WASM and to native N-API modules

Rust <-> Remix Sandbox Now with both native Rust and WASM versions! If you want to combine the Web Fundamentals & Modern UX of Remix together with the

Ben Wishovich 26 Dec 30, 2022
Junon.io - 2D space sandbox survival

Junon.io Junon.io is a co-op multiplayer survival game where your goal is to build your own space-station, grow your colony, and defend it against hos

null 1 Oct 29, 2022
A movie schema sandbox for playing with EdgeDB and the EdgeQL query builder, pre-loaded with MCU data

The EdgeDB MCU sandbox ?? This is a sandbox for playing with EdgeDB and the EdgeQL query builder. It includes a simple movie database schema (dbschema

EdgeDB 13 Nov 9, 2022
An obsidian plugin that allows code blocks executed interactively in sandbox like jupyter notebooks. Supported language rust、kotlin、python、Javascript、TypeScript etc.

Obsidian Code Emitter This plugin allows code blocks executed interactively like jupyter notebooks. Currently, support languages: Rust Kotlin JavaScri

YiiSh 38 Dec 28, 2022
Simple code sandbox for your website.

Live Coding Sessions It is just a simple desk app which puts 3 apps together (code, audio, draw) in a responsiveness way, so you can have all at once,

VastJS 5 Oct 23, 2022
Ergonomic, chaining-based Typescript framework for quick API development for Fastify

Ergonomic, chaining-based Typescript framework for quick API development for Fastify Installation > pnpm add @t3ned/channel Usage // index.ts import

T3NED 6 Aug 2, 2022
An easy-to-read, quick reference for JS best practices, accepted coding standards, and links around the Web

Feel free to contribute! Where? http://www.jstherightway.org Why? Today we have a bunch of websites running JavaScript. I think we need a place to put

BrazilJS 8.5k Jan 1, 2023
A quick capture plugin for Obsidian, all data from your daily notes.

Obsidian Memos 中文文档 A new way for you to quick capture an idea in Obsidian. Which is highly based on the awesome open source project: memos and awesom

Boninall 551 Jan 3, 2023
A quick start Create React App template with react-router-dom, material-ui, gh-pages and firebase

A quick start Create React App template with react-router-dom, material-ui, gh-pages and firebase. With google authentication, routing and deployment capabilities built in.

Hussain Pettiwala 5 Feb 22, 2022
This app offers users a quick way to check the current temperature and humidity of any location in the world.

Pretty Weather App This app offers users a quick way to check weather data for any location in the world. The specific data provided by the app includ

Benjamin Semah 3 Jun 7, 2022