- Notifications
You must be signed in to change notification settings - Fork127
Safely execute untrusted Javascript in your Javascript, and execute synchronous code that uses async functions
License
justjake/quickjs-emscripten
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Javascript/Typescript bindings for QuickJS, a modern Javascript interpreter,compiled to WebAssembly.
- Safely evaluate untrusted Javascript (supportsmost of ES2023).
- Create and manipulate values inside the QuickJS runtime (more).
- Expose host functions to the QuickJS runtime (more).
- Execute synchronous code that uses asynchronous functions, withasyncify.
- Supports browsers, NodeJS, Deno, Bun, Cloudflare Workers, QuickJS (viaquickjs-for-quickjs).
Github |NPM |API Documentation |Variants |Examples
import{getQuickJS}from"quickjs-emscripten"asyncfunctionmain(){constQuickJS=awaitgetQuickJS()constvm=QuickJS.newContext()constworld=vm.newString("world")vm.setProp(vm.global,"NAME",world)world.dispose()constresult=vm.evalCode(`"Hello " + NAME + "!"`)if(result.error){console.log("Execution failed:",vm.dump(result.error))result.error.dispose()}else{console.log("Success:",vm.dump(result.value))result.value.dispose()}vm.dispose()}main()
- quickjs-emscripten
Install fromnpm:npm install --save quickjs-emscripten oryarn add quickjs-emscripten.
The root entrypoint of this library is thegetQuickJS function, which returnsa promise that resolves to aQuickJSWASMModule whenthe QuickJS WASM module is ready.
OncegetQuickJS has been awaited at least once, you also can use thegetQuickJSSyncfunction to directly access the singleton in your synchronous code.
import{getQuickJS,shouldInterruptAfterDeadline}from"quickjs-emscripten"getQuickJS().then((QuickJS)=>{constresult=QuickJS.evalCode("1 + 1",{shouldInterrupt:shouldInterruptAfterDeadline(Date.now()+1000),memoryLimitBytes:1024*1024,})console.log(result)})
You can useQuickJSContextto build a scripting environment by modifying globals and exposing functionsinto the QuickJS interpreter.
EachQuickJSContext instance has its own environment -- globals, built-inclasses -- and actions from one context won't leak into other contexts orruntimes (with one exception, seeAsyncify).
Every context is created inside aQuickJSRuntime.A runtime represents a Javascript heap, and you can even share values betweencontexts in the same runtime.
constvm=QuickJS.newContext()letstate=0constfnHandle=vm.newFunction("nextId",()=>{returnvm.newNumber(++state)})vm.setProp(vm.global,"nextId",fnHandle)fnHandle.dispose()constnextId=vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`))console.log("vm result:",vm.getNumber(nextId),"native state:",state)nextId.dispose()vm.dispose()
When you create a context from a top-level API like in the example above,instead of by callingruntime.newContext(), a runtime is automatically createdfor the lifetime of the context, and disposed of when you dispose the context.
The runtime has APIs for CPU and memory limits that apply to all contexts withinthe runtime in aggregate. You can also use the runtime to configure EcmaScriptmodule loading.
construntime=QuickJS.newRuntime()// "Should be enough for everyone" -- attributed to B. Gatesruntime.setMemoryLimit(1024*640)// Limit stack sizeruntime.setMaxStackSize(1024*320)// Interrupt computation after 1024 calls to the interrupt handlerletinterruptCycles=0runtime.setInterruptHandler(()=>++interruptCycles>1024)// Toy module system that always returns the module name// as the default exportruntime.setModuleLoader((moduleName)=>`export default '${moduleName}'`)constcontext=runtime.newContext()constok=context.evalCode(`import fooName from './foo.js'globalThis.result = fooName`)context.unwrapResult(ok).dispose()// logs "foo.js"console.log(context.getProp(context.global,"result").consume(context.dump))context.dispose()runtime.dispose()
When you evaluate code as an ES Module, the result will be a handle to themodule's exports, or a handle to a promise that resolves to the module'sexports if the module depends on a top-level await.
constcontext=QuickJS.newContext()constresult=context.evalCode(` export const name = 'Jake' export const favoriteBean = 'wax bean' export default 'potato'`,"jake.js",{type:"module"},)constmoduleExports=context.unwrapResult(result)console.log(context.dump(moduleExports))// -> { name: 'Jake', favoriteBean: 'wax bean', default: 'potato' }moduleExports.dispose()
Many methods in this library return handles to memory allocated inside theWebAssembly heap. These types cannot be garbage-collected as usual inJavascript. Instead, you must manually manage their memory by calling a.dispose() method to free the underlying resources. Once a handle has beendisposed, it cannot be used anymore. Note that in the example above, we call.dispose() on each handle once it is no longer needed.
CallingQuickJSContext.dispose() will throw a RuntimeError if you've forgotten todispose any handles associated with that VM, so it's good practice to create anew VM instance for each of your tests, and to callvm.dispose() at the endof every test.
constvm=QuickJS.newContext()constnumberHandle=vm.newNumber(42)// Note: numberHandle not disposed, so it leaks memory.vm.dispose()// throws RuntimeError: abort(Assertion failed: list_empty(&rt->gc_obj_list), at: quickjs/quickjs.c,1963,JS_FreeRuntime)
Here are some strategies to reduce the toil of calling.dispose() on eachhandle you create:
Theusing statement is a Stage 3 (as of 2023-12-29) proposal for Javascript that declares a constant variable and automatically calls the[Symbol.dispose]() method of an object when it goes out of scope. Read morein this Typescript release announcement. Here's the "Interfacing with the interpreter" example re-written usingusing:
usingvm=QuickJS.newContext()letstate=0// The block here isn't needed for correctness, but it shows// how to get a tighter bound on the lifetime of `fnHandle`.{ usingfnHandle=vm.newFunction("nextId",()=>{returnvm.newNumber(++state)})vm.setProp(vm.global,"nextId",fnHandle)// fnHandle.dispose() is called automatically when the block exits}usingnextId=vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`))console.log("vm result:",vm.getNumber(nextId),"native state:",state)// nextId.dispose() is called automatically when the block exits// vm.dispose() is called automatically when the block exits
AScopeinstance manages a set of disposables and calls their.dispose()method in the reverse order in which they're added to the scope. Here's the"Interfacing with the interpreter" example re-written usingScope:
Scope.withScope((scope)=>{constvm=scope.manage(QuickJS.newContext())letstate=0constfnHandle=scope.manage(vm.newFunction("nextId",()=>{returnvm.newNumber(++state)}),)vm.setProp(vm.global,"nextId",fnHandle)constnextId=scope.manage(vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)))console.log("vm result:",vm.getNumber(nextId),"native state:",state)// When the withScope block exits, it calls scope.dispose(), which in turn calls// the .dispose() methods of all the disposables managed by the scope.})
You can also createScope instances withnew Scope() if you want to managecallingscope.dispose() yourself.
Lifetime.consumeis sugar for the common pattern of using a handle and thenimmediately disposing of it.Lifetime.consume takes amap function thatproduces a result of any type. Themap fuction is called with the handle,then the handle is disposed, then the result is returned.
Here's the "Interfacing with interpreter" example re-written using.consume():
constvm=QuickJS.newContext()letstate=0vm.newFunction("nextId",()=>{returnvm.newNumber(++state)}).consume((fnHandle)=>vm.setProp(vm.global,"nextId",fnHandle))vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)).consume((nextId)=>console.log("vm result:",vm.getNumber(nextId),"native state:",state),)vm.dispose()
Generally working withScope leads to more straight-forward code, butLifetime.consume can be handy sugar as part of a method call chain.
To add APIs inside the QuickJS environment, you'll need tocreate objects todefine the shape of your API, andadd properties andfunctions to those objectsto allow code inside QuickJS to call code on the host.ThenewFunction documentation covers writing functions in detail.
By default, no host functionality is exposed to code running inside QuickJS.
constvm=QuickJS.newContext()// `console.log`constlogHandle=vm.newFunction("log",(...args)=>{constnativeArgs=args.map(vm.dump)console.log("QuickJS:", ...nativeArgs)})// Partially implement `console` objectconstconsoleHandle=vm.newObject()vm.setProp(consoleHandle,"log",logHandle)vm.setProp(vm.global,"console",consoleHandle)consoleHandle.dispose()logHandle.dispose()vm.unwrapResult(vm.evalCode(`console.log("Hello from QuickJS!")`)).dispose()
To expose an asynchronous function thatreturns a promise to callers withinQuickJS, your function can return the handle of aQuickJSDeferredPromisecreated viacontext.newPromise().
When you resolve aQuickJSDeferredPromise -- and generally whenever asyncbehavior completes for the VM -- pending listeners inside QuickJS may notexecute immediately. Your code needs to explicitly callruntime.executePendingJobs() to resume execution inside QuickJS. This APIgives your code maximum control toschedule when QuickJS will block the host'sevent loop by resuming execution.
To work with QuickJS handles that contain a promise inside the environment,there are two options:
You can synchronously peek into a QuickJS promise handle and get its statewithout introducing asynchronous host code, described by the typeJSPromiseState:
typeJSPromiseState=|{type:"pending";error:Error}|{type:"fulfilled";value:QuickJSHandle;notAPromise?:boolean}|{type:"rejected";error:QuickJSHandle}
The result conforms to theSuccessOrFail type returned bycontext.evalCode, so you can usecontext.unwrapResult(context.getPromiseState(promiseHandle)) to assert a promise is settled successfully and retrieve its value. Callingcontext.unwrapResult on a pending or rejected promise will throw an error.
constpromiseHandle=context.evalCode(`Promise.resolve(42)`)constresultHandle=context.unwrapResult(context.getPromiseState(promiseHandle))context.getNumber(resultHandle)===42// trueresultHandle.dispose()promiseHandle.dispose()
You can convert the QuickJSHandle into a native promise usingcontext.resolvePromise(). Take care with this API to avoid 'deadlocks' wherethe host awaits a guest promise, but the guest cannot make progress until thehost callsruntime.executePendingJobs(). The simplest way to avoid this kindof deadlock is to always scheduleexecutePendingJobs after any promise issettled.
constvm=QuickJS.newContext()constfakeFileSystem=newMap([["example.txt","Example file content"]])// Function that simulates reading data asynchronouslyconstreadFileHandle=vm.newFunction("readFile",(pathHandle)=>{constpath=vm.getString(pathHandle)constpromise=vm.newPromise()setTimeout(()=>{constcontent=fakeFileSystem.get(path)promise.resolve(vm.newString(content||""))},100)// IMPORTANT: Once you resolve an async action inside QuickJS,// call runtime.executePendingJobs() to run any code that was// waiting on the promise or callback.promise.settled.then(vm.runtime.executePendingJobs)returnpromise.handle})readFileHandle.consume((handle)=>vm.setProp(vm.global,"readFile",handle))// Evaluate code that uses `readFile`, which returns a promiseconstresult=vm.evalCode(`(async () => { const content = await readFile('example.txt') return content.toUpperCase()})()`)constpromiseHandle=vm.unwrapResult(result)// Convert the promise handle into a native promise and await it.// If code like this deadlocks, make sure you are calling// runtime.executePendingJobs appropriately.constresolvedResult=awaitvm.resolvePromise(promiseHandle)promiseHandle.dispose()constresolvedHandle=vm.unwrapResult(resolvedResult)console.log("Result:",vm.getString(resolvedHandle))resolvedHandle.dispose()
Sometimes, we want to create a function that's synchronous from the perspectiveof QuickJS, but prefer to implement that functionasynchronously in your hostcode. The most obvious use-case is for EcmaScript module loading. The underlyingQuickJS C library expects the module loader function to return synchronously,but loading data synchronously in the browser or server is somewhere between "abad idea" and "impossible". QuickJS also doesn't expose an API to "pause" theexecution of a runtime, and adding such an API is tricky due to the VM'simplementation.
As a work-around, we provide an alternate build of QuickJS processed byEmscripten/Binaryen'sASYNCIFYcompiler transform. Here's how Emscripten's documentation describes Asyncify:
Asyncify lets synchronous C or C++ code interact with asynchronous [host] JavaScript. This allows things like:
- A synchronous call in C that yields to the event loop, which allows browser events to be handled.
- A synchronous call in C that waits for an asynchronous operation in [host] JS to complete.
Asyncify automatically transforms ... code into a form that can be paused andresumed ..., so that it is asynchronous (hence the name “Asyncify”) even though[it is written] in a normal synchronous way.
This means we can suspend anentire WebAssembly module (which could containmultiple runtimes and contexts) while our host Javascript loads dataasynchronously, and then resume execution once the data load completes. This isa very handy superpower, but it comes with a couple of major limitations:
An asyncified WebAssembly module can only suspend to wait for a singleasynchronous call at a time. You may call back into a suspended WebAssemblymodule eg. to create a QuickJS value to return a result, but the system willcrash if this call tries to suspend again. Take a look at Emscripten's documentationonreentrancy.
Asyncified code is bigger and runs slower. The asyncified build ofQuickjs-emscripten library is 1M, 2x larger than the 500K of the defaultversion. There may be room for furtheroptimizationOf our build in the future.
To use asyncify features, use the following functions:
- newAsyncRuntime: create a runtime inside a new WebAssembly module.
- newAsyncContext: create runtime and context together inside a newWebAssembly module.
- newQuickJSAsyncWASMModule: create an empty WebAssembly module.
These functions are asynchronous because they always create a new underlyingWebAssembly module so that each instance can suspend and resume independently,and instantiating a WebAssembly module is an async operation. This also addssubstantial overhead compared to creating a runtime or context inside anexisting module; if you only need to wait for a single async action at a time,you can create a single top-level module and create runtimes or contexts insideof it.
Here's an example of valuating a script that loads React asynchronously as an ESmodule. In our example, we're loading from the filesystem for reproducibility,but you can use this technique to load usingfetch.
constmodule=awaitnewQuickJSAsyncWASMModule()construntime=module.newRuntime()constpath=awaitimport("path")const{promises:fs}=awaitimport("fs")constimportsPath=path.join(__dirname,"../examples/imports")+"/"// Module loaders can return promises.// Execution will suspend until the promise resolves.runtime.setModuleLoader((moduleName)=>{constmodulePath=path.join(importsPath,moduleName)if(!modulePath.startsWith(importsPath)){thrownewError("out of bounds")}console.log("loading",moduleName,"from",modulePath)returnfs.readFile(modulePath,"utf-8")})// evalCodeAsync is required when execution may suspend.constcontext=runtime.newContext()constresult=awaitcontext.evalCodeAsync(`import * as React from 'esm.sh/react@17'import * as ReactDOMServer from 'esm.sh/react-dom@17/server'const e = React.createElementglobalThis.html = ReactDOMServer.renderToStaticMarkup( e('div', null, e('strong', null, 'Hello world!')))`)context.unwrapResult(result).dispose()consthtml=context.getProp(context.global,"html").consume(context.getString)console.log(html)// <div><strong>Hello world!</strong></div>
Here's an example of turning an async function into a sync function inside theVM.
constcontext=awaitnewAsyncContext()constpath=awaitimport("path")const{promises:fs}=awaitimport("fs")constimportsPath=path.join(__dirname,"../examples/imports")+"/"constreadFileHandle=context.newAsyncifiedFunction("readFile",async(pathHandle)=>{constpathString=path.join(importsPath,context.getString(pathHandle))if(!pathString.startsWith(importsPath)){thrownewError("out of bounds")}constdata=awaitfs.readFile(pathString,"utf-8")returncontext.newString(data)})readFileHandle.consume((fn)=>context.setProp(context.global,"readFile",fn))// evalCodeAsync is required when execution may suspend.constresult=awaitcontext.evalCodeAsync(`// Not a promise! Sync! vvvvvvvvvvvvvvvvvvvvconst data = JSON.parse(readFile('data.json'))data.map(x => x.toUpperCase()).join(' ')`)constupperCaseData=context.unwrapResult(result).consume(context.getString)console.log(upperCaseData)// 'VERY USEFUL DATA'
This library is complicated to use, so please consider automated testing yourimplementation. We highly writing your test suite to run with both the "release"build variant of quickjs-emscripten, and also theDEBUG_SYNC build variant.The debug sync build variant has extra instrumentation code for detecting memoryleaks.
The classTestQuickJSWASMModule exposes the memory leak detection API,although this API is only accurate when usingDEBUG_SYNC variant. You can alsoenabledebug logging to help diagnose failures.
// Define your test suite in a function, so that you can test against// different module loaders.functionmyTests(moduleLoader:()=>Promise<QuickJSWASMModule>){letQuickJS:TestQuickJSWASMModulebeforeEach(async()=>{// Get a unique TestQuickJSWASMModule instance for each test.constwasmModule=awaitmoduleLoader()QuickJS=newTestQuickJSWASMModule(wasmModule)})afterEach(()=>{// Assert that the test disposed all handles. The DEBUG_SYNC build// variant will show detailed traces for each leak.QuickJS.assertNoMemoryAllocated()})it("works well",()=>{// TODO: write a test using QuickJSconstcontext=QuickJS.newContext()context.unwrapResult(context.evalCode("1 + 1")).dispose()context.dispose()})}// Run the test suite against a matrix of module loaders.describe("Check for memory leaks with QuickJS DEBUG build",()=>{constmoduleLoader=memoizePromiseFactory(()=>newQuickJSWASMModule(DEBUG_SYNC))myTests(moduleLoader)})describe("Realistic test with QuickJS RELEASE build",()=>{myTests(getQuickJS)})
For more testing examples, please explore the typescript source ofquickjs-emscripten repository.
The mainquickjs-emscripten package includes several build variants of the WebAssembly module:
RELEASE...build variants should be used in production. They offer better performance and smaller file size compared toDEBUG...build variants.RELEASE_SYNC: This is the default variant used when you don't explicitly provide one. It offers the fastest performance and smallest file size.RELEASE_ASYNC: The default variant if you needasyncify magic, which comes at a performance cost. See the asyncify docs for details.
DEBUG...build variants can be helpful during development and testing. They include source maps and assertions for catching bugs in your code. We recommend running your tests withboth a debug build variant and the release build variant you'll use in production.DEBUG_SYNC: Instrumented to detect memory leaks, in addition to assertions and source maps.DEBUG_ASYNC: Anasyncify variant with source maps.
To use a variant, callnewQuickJSWASMModule ornewQuickJSAsyncWASMModule with the variant object. These functions return a promise that resolves to aQuickJSWASMModule, the same asgetQuickJS.
import{newQuickJSWASMModule,newQuickJSAsyncWASMModule,RELEASE_SYNC,DEBUG_SYNC,RELEASE_ASYNC,DEBUG_ASYNC,}from"quickjs-emscripten"constQuickJSReleaseSync=awaitnewQuickJSWASMModule(RELEASE_SYNC)constQuickJSDebugSync=awaitnewQuickJSWASMModule(DEBUG_SYNC)constQuickJSReleaseAsync=awaitnewQuickJSAsyncWASMModule(RELEASE_ASYNC)constQuickJSDebugAsync=awaitnewQuickJSAsyncWASMModule(DEBUG_ASYNC)for(constquickjsof[QuickJSReleaseSync,QuickJSDebugSync,QuickJSReleaseAsync,QuickJSDebugAsync,]){constvm=quickjs.newContext()constresult=vm.unwrapResult(vm.evalCode("1 + 1")).consume(vm.getNumber)console.log(result)vm.dispose()quickjs.dispose()}
Including 4 different copies of the WebAssembly module in the main package gives it an install size ofabout 9.04mb. If you're building a CLI package or library of your own, or otherwise don't need to include 4 different variants in yournode_modules, you can switch to thequickjs-emscripten-core package, which contains only the Javascript code for this library, and install one (or more) variants a-la-carte as separate packages.
The most minimal setup would be to installquickjs-emscripten-core and@jitl/quickjs-wasmfile-release-sync (1.3mb total):
yarn add quickjs-emscripten-core @jitl/quickjs-wasmfile-release-syncdu -h node_modules# 640K node_modules/@jitl/quickjs-wasmfile-release-sync# 80K node_modules/@jitl/quickjs-ffi-types# 588K node_modules/quickjs-emscripten-core# 1.3M node_modules
Then, you can use quickjs-emscripten-core'snewQuickJSWASMModuleFromVariant to create a QuickJS module (seethe minimal example):
// src/quickjs.mjsimport{newQuickJSWASMModuleFromVariant}from"quickjs-emscripten-core"importRELEASE_SYNCfrom"@jitl/quickjs-wasmfile-release-sync"exportconstQuickJS=awaitnewQuickJSWASMModuleFromVariant(RELEASE_SYNC)// src/app.mjsimport{QuickJS}from"./quickjs.mjs"console.log(QuickJS.evalCode("1 + 1"))
See thedocumentation of quickjs-emscripten-core for more details and the list of variant packages.
To run QuickJS, we need to load a WebAssembly module into the host Javascript runtime's memory (usually as an ArrayBuffer or TypedArray) andcompile it to aWebAssembly.Module. This means we need to find the file path or URI of the WebAssembly module, and then read it using an API likefetch (browser) orfs.readFile (NodeJS).quickjs-emscripten tries to handle this automatically using patterns likenew URL('./local-path', import.meta.url) that work in the browser or are handled automatically by bundlers, or__dirname in NodeJS, but you may need to configure this manually if these don't work in your environment, or you want more control about how the WebAssembly module is loaded.
To customize the loading of an existing variant, create a new variant with your loading settings usingnewVariant, passingCustomizeVariantOptions. For example, you need to customize loading in Cloudflare Workers (seethe full example).
import{newQuickJSWASMModule,DEBUG_SYNCasbaseVariant,newVariant}from"quickjs-emscripten"importcloudflareWasmModulefrom"./DEBUG_SYNC.wasm"importcloudflareWasmModuleSourceMapfrom"./DEBUG_SYNC.wasm.map.txt"/** * We need to make a new variant that directly passes the imported WebAssembly.Module * to Emscripten. Normally we'd load the wasm file as bytes from a URL, but * that's forbidden in Cloudflare workers. */constcloudflareVariant=newVariant(baseVariant,{wasmModule:cloudflareWasmModule,wasmSourceMapData:cloudflareWasmModuleSourceMap,})
quickjs-ng/quickjs (aka quickjs-ng) is a fork of the originalbellard/quickjs under active development. It implements more EcmaScript standards and removes some of quickjs's custom language features like BigFloat.
There are several variants of quickjs-ng available, and quickjs-emscripten may switch to using quickjs-ng by default in the future. Seethe list of variants.
You can use quickjs-emscripten directly from an HTML file in two ways:
Import it in an ES Module script tag
<!doctype html><!-- Import from a ES Module CDN --><scripttype="module">import{getQuickJS}from"https://esm.sh/quickjs-emscripten@0.25.0"constQuickJS=awaitgetQuickJS()console.log(QuickJS.evalCode("1+1"))</script>
In edge cases, you might want to use the IIFE build which provides QuickJS as the global
QJS. You should probably use the ES module though, any recent browser supports it.<!doctype html><!-- Add a script tag to load the library as the QJS global --><scriptsrc="https://cdn.jsdelivr.net/npm/quickjs-emscripten@0.25.0/dist/index.global.js"type="text/javascript"></script><!-- Then use the QJS global in a script tag --><scripttype="text/javascript">QJS.getQuickJS().then((QuickJS)=>{console.log(QuickJS.evalCode("1+1"))})</script>
Debug logging can be enabled globally, or for specific runtimes. You need to use a DEBUG build variant of the WebAssembly module to see debug log messages from the C part of this library.
import{newQuickJSWASMModule,DEBUG_SYNC}from"quickjs-emscripten"constQuickJS=awaitnewQuickJSWASMModule(DEBUG_SYNC)
With quickjs-emscripten-core:
import{newQuickJSWASMModuleFromVariant}from"quickjs-emscripten-core"importDEBUG_SYNCfrom"@jitl/quickjs-wasmfile-debug-sync"constQuickJS=awaitnewQuickJSWASMModuleFromVariant(DEBUG_SYNC)
To enable debug logging globally, callsetDebugMode. This affects global Javascript parts of the library, like the module loader and asyncify internals, and is inherited by runtimes created after the call.
import{setDebugMode}from"quickjs-emscripten"setDebugMode(true)
With quickjs-emscripten-core:
import{setDebugMode}from"quickjs-emscripten-core"setDebugMode(true)
To enable debug logging for a specific runtime, callsetDebugModeRt. This affects only the runtime and its associated contexts.
construntime=QuickJS.newRuntime()runtime.setDebugMode(true)constcontext=QuickJS.newContext()context.runtime.setDebugMode(true)
quickjs-emscripten and related packages should work in any environment that supports ES2020.
- Browsers: we estimate support for the following browser versions. See theglobal-iife andesmodule HTML examples.
- Chrome 63+
- Edge 79+
- Safari 11.1+
- Firefox 58+
- NodeJS: requires v16.0.0 or later for WebAssembly compatibility. Tested with node@18. See thenode-typescript andnode-minimal examples.
- Typescript: tested with typescript@4.5.5 and typescript@5.3.3. See thenode-typescript example.
- Vite: tested with vite@5.0.10. See theVite/Vue example.
- Create react app: tested with react-scripts@5.0.1. See thecreate-react-app example.
- Webpack: tested with webpack@5.89.0 via create-react-app.
- Cloudflare Workers: tested with wrangler@3.22.1. See theCloudflare Workers example.
- Deno: tested with deno 1.39.1. See theDeno example.
Github |NPM |API Documentation |Variants |Examples
This was inspired by seeinghttps://github.com/maple3142/duktape-evalon Hacker News and Figma'sblogposts about using building a Javascript plugin runtime:
- How Figma built the Figma plugin system: Describes the LowLevelJavascriptVm interface.
- An update on plugin security: Figma switches to QuickJS.
Stability: Because the version number of this project is below1.0.0,*expect occasional breaking API changes.
Security: This project makes every effort to be secure, but has not beenaudited. Please use with care in production settings.
Roadmap: I work on this project in my free time, for fun. Here's I'mthinking comes next. Last updated 2022-03-18.
Further work on module loading APIs:
- Create modules via Javascript, instead of source text.
- Scan source text for imports, for ahead of time or concurrent loading.(This is possible with third-party tools, so lower priority.)
Higher-level tools for reading QuickJS values:
- Type guard functions:
context.isArray(handle),context.isPromise(handle), etc. - Iteration utilities:
context.getIterable(handle),context.iterateObjectEntries(handle).This better supports user-level code to deserialize complex handle objects.
- Type guard functions:
Higher-level tools for creating QuickJS values:
- Devise a way to avoid needing to mess around with handles when setting upthe environment.
- Consider integratingquickjs-emscripten-syncfor automatic translation.
- Consider class-based or interface-type-based marshalling.
SQLite integration.
- Duktape wrapped in Wasm:https://github.com/maple3142/duktape-eval/blob/main/src/Makefile
- QuickJS wrapped in C++:https://github.com/ftk/quickjspp
This library is implemented in two languages: C (compiled to WASM withEmscripten), and Typescript.
You will neednode,yarn,make, andemscripten to build this project.
The ./c directory contains C code that wraps the QuickJS C library (in ./quickjs).Public functions (those starting withQTS_) in ./c/interface.c areautomatically exported to native code (via a generated header) and toTypescript (via a generated FFI class). See ./generate.ts for how this works.
The C code builds withemscripten (usingemcc), to produce WebAssembly.The version of Emscripten used by the project is defined in templates/Variant.mk.
- On ARM64, you should install
emscriptenon your machine. For example on macOS,brew install emscripten. - Ifthe correct version of emcc is not in your PATH, compilation falls back to using Docker.On ARM64, this is 10-50x slower than native compilation, but it's just fine on x64.
We produce multiple build variants of the C code compiled to WebAssembly using atemplate script the ./packages directory. Each build variant uses its own copy of a Makefileto build the C code. The Makefile is generated from a template in ./templates/Variant.mk.
Related NPM scripts:
yarn vendor:updateupdates vendor/quickjs and vendor/quickjs-ng to the latest versions on Github.yarn build:codegenupdates the ./packages from the template script./prepareVariants.tsand Variant.mk.yarn build:packagesbuilds the variant packages in parallel.
The Javascript/Typescript code is also organized into several NPM packages in ./packages:
- ./packages/quickjs-ffi-types: Low-level types that define the FFI interface to the C code.Each variant exposes an API conforming to these types that's consumed by the higher-level library.
- ./packages/quickjs-emscripten-core: The higher-level Typescript that implements the user-facing abstractions of the library.This package doesn't link directly to the WebAssembly/C code; callers must provide a build variant.
- ./packages/quicks-emscripten: The main entrypoint of the library, which provides the
getQuickJSfunction.This package combines quickjs-emscripten-core with platform-appropriate WebAssembly/C code.
Related NPM scripts:
yarn checkruns all available checks (build, format, tests, etc).yarn buildbuilds all the packages and generates the docs.yarn testruns the tests for all packages.yarn test:fastruns the tests using only fast build variants.
yarn docgenerates the docs into./doc.yarn doc:servepreviews the current./docin a browser.
yarn prettierformats the repo.
Just runyarn set version from sources to upgrade the Yarn release.
About
Safely execute untrusted Javascript in your Javascript, and execute synchronous code that uses async functions
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.