{"_id":"@tootallnate/quickjs-emscripten","_rev":"3002945","name":"@tootallnate/quickjs-emscripten","description":"Javascript/Typescript bindings for QuickJS, a modern Javascript interpreter, compiled to WebAssembly.","dist-tags":{"latest":"0.23.0"},"maintainers":[{"name":"tootallnate","email":"nathan@tootallnate.net"}],"time":{"modified":"2023-09-15T10:00:23.000Z","created":"2023-07-18T08:26:47.468Z","0.23.0":"2023-07-18T08:26:47.468Z"},"users":{},"repository":{"type":"git","url":"git+https://github.com/justjake/quickjs-emscripten.git"},"versions":{"0.23.0":{"name":"@tootallnate/quickjs-emscripten","version":"0.23.0","main":"dist/index.js","sideEffects":false,"license":"MIT","keywords":["eval","quickjs","vm","interpreter","runtime","safe","emscripten","wasm"],"repository":{"type":"git","url":"git+https://github.com/justjake/quickjs-emscripten.git"},"scripts":{"tarball":"make build/quickjs-emscripten.tgz","clean":"make clean","tsc":"tsc","build":"make dist","doc":"typedoc","test":"TS_NODE_TRANSPILE_ONLY=true mocha 'ts/**/*.test.ts'","test-dist":"cd dist && TS_NODE_TRANSPILE_ONLY=true mocha --require source-map-support/register *.test.js","test-fast":"TEST_NO_ASYNC=true yarn test 'ts/**/*.test.ts'","test-all":"TEST_LEAK=1 yarn test && TEST_LEAK=1 yarn test-dist","prettier":"prettier --write .","prettier-check":"prettier --check .","update-quickjs":"git subtree pull --prefix=quickjs --squash git@github.com:bellard/quickjs.git master","smoketest-node":"yarn tarball && ./scripts/smoketest-node.sh","smoketest-cra":"yarn tarball && ./scripts/smoketest-website.sh"},"devDependencies":{"@types/emscripten":"^1.38.0","@types/fs-extra":"^9.0.13","@types/mocha":"^5.2.7","@types/node":"^13.1.4","fs-extra":"^10.0.1","markserv":"^1.17.4","mocha":"7.2.0","node-fetch-commonjs":"^3.1.1","prettier":"2.8.4","source-map-support":"^0.5.21","ts-node":"^10.9.1","typedoc":"^0.22.0","typedoc-plugin-inline-sources":"^1.0.1","typedoc-plugin-markdown":"^3.11.12","typescript":"^4.9.5"},"types":"./dist/index.d.ts","gitHead":"891a55e8df93a667e5980863f2995e8bfef54872","description":"Javascript/Typescript bindings for QuickJS, a modern Javascript interpreter, compiled to WebAssembly.","bugs":{"url":"https://github.com/justjake/quickjs-emscripten/issues"},"homepage":"https://github.com/justjake/quickjs-emscripten#readme","_id":"@tootallnate/quickjs-emscripten@0.23.0","_nodeVersion":"16.20.1","_npmVersion":"8.19.4","dist":{"shasum":"db4ecfd499a9765ab24002c3b696d02e6d32a12c","size":663737,"noattachment":false,"key":"/@tootallnate/quickjs-emscripten/-/@tootallnate/quickjs-emscripten-0.23.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/@tootallnate/quickjs-emscripten/download/@tootallnate/quickjs-emscripten-0.23.0.tgz"},"_npmUser":{"name":"tootallnate","email":"nathan@tootallnate.net"},"directories":{},"maintainers":[{"name":"tootallnate","email":"nathan@tootallnate.net"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/quickjs-emscripten_0.23.0_1689668807300_0.47508671517826206"},"_hasShrinkwrap":false,"_cnpmcore_publish_time":"2023-07-18T08:26:47.468Z","publish_time":1689668807468,"_source_registry_name":"default","_cnpm_publish_time":1689668807468}},"readme":"# quickjs-emscripten\n\nJavascript/Typescript bindings for QuickJS, a modern Javascript interpreter,\ncompiled to WebAssembly.\n\n- Safely evaluate untrusted Javascript (up to ES2020).\n- Create and manipulate values inside the QuickJS runtime ([more][values]).\n- Expose host functions to the QuickJS runtime ([more][functions]).\n- Execute synchronous code that uses asynchronous functions, with [asyncify][asyncify].\n\n[Github] | [NPM] | [API Documentation][api] | [Examples][tests]\n\n```typescript\nimport { getQuickJS } from \"quickjs-emscripten\"\n\nasync function main() {\n  const QuickJS = await getQuickJS()\n  const vm = QuickJS.newContext()\n\n  const world = vm.newString(\"world\")\n  vm.setProp(vm.global, \"NAME\", world)\n  world.dispose()\n\n  const result = vm.evalCode(`\"Hello \" + NAME + \"!\"`)\n  if (result.error) {\n    console.log(\"Execution failed:\", vm.dump(result.error))\n    result.error.dispose()\n  } else {\n    console.log(\"Success:\", vm.dump(result.value))\n    result.value.dispose()\n  }\n\n  vm.dispose()\n}\n\nmain()\n```\n\n[github]: https://github.com/justjake/quickjs-emscripten\n[npm]: https://www.npmjs.com/package/quickjs-emscripten\n[api]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md\n[tests]: https://github.com/justjake/quickjs-emscripten/blob/main/ts/quickjs.test.ts\n[values]: #interfacing-with-the-interpreter\n[asyncify]: #asyncify\n[functions]: #exposing-apis\n\n## Usage\n\nInstall from `npm`: `npm install --save quickjs-emscripten` or `yarn add quickjs-emscripten`.\n\nThe root entrypoint of this library is the `getQuickJS` function, which returns\na promise that resolves to a [QuickJS singleton](./doc/classes/quickjs.md) when\nthe QuickJS WASM module is ready.\n\nOnce `getQuickJS` has been awaited at least once, you also can use the `getQuickJSSync`\nfunction to directly access the singleton engine in your synchronous code.\n\n### Safely evaluate Javascript code\n\nSee [QuickJS.evalCode](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/quickjs.md#evalcode)\n\n```typescript\nimport { getQuickJS, shouldInterruptAfterDeadline } from \"quickjs-emscripten\"\n\ngetQuickJS().then((QuickJS) => {\n  const result = QuickJS.evalCode(\"1 + 1\", {\n    shouldInterrupt: shouldInterruptAfterDeadline(Date.now() + 1000),\n    memoryLimitBytes: 1024 * 1024,\n  })\n  console.log(result)\n})\n```\n\n### Interfacing with the interpreter\n\nYou can use [QuickJSContext](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/QuickJSContext.md)\nto build a scripting environment by modifying globals and exposing functions\ninto the QuickJS interpreter.\n\nEach `QuickJSContext` instance has its own environment -- globals, built-in\nclasses -- and actions from one context won't leak into other contexts or\nruntimes (with one exception, see [Asyncify][asyncify]).\n\nEvery context is created inside a\n[QuickJSRuntime](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/QuickJSRuntime.md).\nA runtime represents a Javascript heap, and you can even share values between\ncontexts in the same runtime.\n\n```typescript\nconst vm = QuickJS.newContext()\nlet state = 0\n\nconst fnHandle = vm.newFunction(\"nextId\", () => {\n  return vm.newNumber(++state)\n})\n\nvm.setProp(vm.global, \"nextId\", fnHandle)\nfnHandle.dispose()\n\nconst nextId = vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`))\nconsole.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n\nnextId.dispose()\nvm.dispose()\n```\n\nWhen you create a context from a top-level API like in the example above,\ninstead of by calling `runtime.newContext()`, a runtime is automatically created\nfor the lifetime of the context, and disposed of when you dispose the context.\n\n#### Runtime\n\nThe runtime has APIs for CPU and memory limits that apply to all contexts within\nthe runtime in aggregate. You can also use the runtime to configure EcmaScript\nmodule loading.\n\n```typescript\nconst runtime = QuickJS.newRuntime()\n// \"Should be enough for everyone\" -- attributed to B. Gates\nruntime.setMemoryLimit(1024 * 640)\n// Limit stack size\nruntime.setMaxStackSize(1024 * 320)\n// Interrupt computation after 1024 calls to the interrupt handler\nlet interruptCycles = 0\nruntime.setInterruptHandler(() => ++interruptCycles > 1024)\n// Toy module system that always returns the module name\n// as the default export\nruntime.setModuleLoader((moduleName) => `export default '${moduleName}'`)\nconst context = runtime.newContext()\nconst ok = context.evalCode(`\nimport fooName from './foo.js'\nglobalThis.result = fooName\n`)\ncontext.unwrapResult(ok).dispose()\n// logs \"foo.js\"\nconsole.log(context.getProp(context.global, \"result\").consume(context.dump))\ncontext.dispose()\nruntime.dispose()\n```\n\n### Memory Management\n\nMany methods in this library return handles to memory allocated inside the\nWebAssembly heap. These types cannot be garbage-collected as usual in\nJavascript. Instead, you must manually manage their memory by calling a\n`.dispose()` method to free the underlying resources. Once a handle has been\ndisposed, it cannot be used anymore. Note that in the example above, we call\n`.dispose()` on each handle once it is no longer needed.\n\nCalling `QuickJSContext.dispose()` will throw a RuntimeError if you've forgotten to\ndispose any handles associated with that VM, so it's good practice to create a\nnew VM instance for each of your tests, and to call `vm.dispose()` at the end\nof every test.\n\n```typescript\nconst vm = QuickJS.newContext()\nconst numberHandle = vm.newNumber(42)\n// Note: numberHandle not disposed, so it leaks memory.\nvm.dispose()\n// throws RuntimeError: abort(Assertion failed: list_empty(&rt->gc_obj_list), at: quickjs/quickjs.c,1963,JS_FreeRuntime)\n```\n\nHere are some strategies to reduce the toil of calling `.dispose()` on each\nhandle you create:\n\n#### Scope\n\nA\n[`Scope`](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/scope.md#class-scope)\ninstance manages a set of disposables and calls their `.dispose()`\nmethod in the reverse order in which they're added to the scope. Here's the\n\"Interfacing with the interpreter\" example re-written using `Scope`:\n\n```typescript\nScope.withScope((scope) => {\n  const vm = scope.manage(QuickJS.newContext())\n  let state = 0\n\n  const fnHandle = scope.manage(\n    vm.newFunction(\"nextId\", () => {\n      return vm.newNumber(++state)\n    })\n  )\n\n  vm.setProp(vm.global, \"nextId\", fnHandle)\n\n  const nextId = scope.manage(vm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)))\n  console.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n\n  // When the withScope block exits, it calls scope.dispose(), which in turn calls\n  // the .dispose() methods of all the disposables managed by the scope.\n})\n```\n\nYou can also create `Scope` instances with `new Scope()` if you want to manage\ncalling `scope.dispose()` yourself.\n\n#### `Lifetime.consume(fn)`\n\n[`Lifetime.consume`](https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/lifetime.md#consume)\nis sugar for the common pattern of using a handle and then\nimmediately disposing of it. `Lifetime.consume` takes a `map` function that\nproduces a result of any type. The `map` fuction is called with the handle,\nthen the handle is disposed, then the result is returned.\n\nHere's the \"Interfacing with interpreter\" example re-written using `.consume()`:\n\n```typescript\nconst vm = QuickJS.newContext()\nlet state = 0\n\nvm.newFunction(\"nextId\", () => {\n  return vm.newNumber(++state)\n}).consume((fnHandle) => vm.setProp(vm.global, \"nextId\", fnHandle))\n\nvm.unwrapResult(vm.evalCode(`nextId(); nextId(); nextId()`)).consume((nextId) =>\n  console.log(\"vm result:\", vm.getNumber(nextId), \"native state:\", state)\n)\n\nvm.dispose()\n```\n\nGenerally working with `Scope` leads to more straight-forward code, but\n`Lifetime.consume` can be handy sugar as part of a method call chain.\n\n### Exposing APIs\n\nTo add APIs inside the QuickJS environment, you'll need to create objects to\ndefine the shape of your API, and add properties and functions to those objects\nto allow code inside QuickJS to call code on the host.\n\nBy default, no host functionality is exposed to code running inside QuickJS.\n\n```typescript\nconst vm = QuickJS.newContext()\n// `console.log`\nconst logHandle = vm.newFunction(\"log\", (...args) => {\n  const nativeArgs = args.map(vm.dump)\n  console.log(\"QuickJS:\", ...nativeArgs)\n})\n// Partially implement `console` object\nconst consoleHandle = vm.newObject()\nvm.setProp(consoleHandle, \"log\", logHandle)\nvm.setProp(vm.global, \"console\", consoleHandle)\nconsoleHandle.dispose()\nlogHandle.dispose()\n\nvm.unwrapResult(vm.evalCode(`console.log(\"Hello from QuickJS!\")`)).dispose()\n```\n\n#### Promises\n\nTo expose an asynchronous function that _returns a promise_ to callers within\nQuickJS, your function can return the handle of a `QuickJSDeferredPromise`\ncreated via `context.newPromise()`.\n\nWhen you resolve a `QuickJSDeferredPromise` -- and generally whenever async\nbehavior completes for the VM -- pending listeners inside QuickJS may not\nexecute immediately. Your code needs to explicitly call\n`runtime.executePendingJobs()` to resume execution inside QuickJS. This API\ngives your code maximum control to _schedule_ when QuickJS will block the host's\nevent loop by resuming execution.\n\nTo work with QuickJS handles that contain a promise inside the environment, you\ncan convert the QuickJSHandle into a native promise using\n`context.resolvePromise()`. Take care with this API to avoid 'deadlocks' where\nthe host awaits a guest promise, but the guest cannot make progress until the\nhost calls `runtime.executePendingJobs()`. The simplest way to avoid this kind\nof deadlock is to always schedule `executePendingJobs` after any promise is\nsettled.\n\n```typescript\nconst vm = QuickJS.newContext()\nconst fakeFileSystem = new Map([[\"example.txt\", \"Example file content\"]])\n\n// Function that simulates reading data asynchronously\nconst readFileHandle = vm.newFunction(\"readFile\", (pathHandle) => {\n  const path = vm.getString(pathHandle)\n  const promise = vm.newPromise()\n  setTimeout(() => {\n    const content = fakeFileSystem.get(path)\n    promise.resolve(vm.newString(content || \"\"))\n  }, 100)\n  // IMPORTANT: Once you resolve an async action inside QuickJS,\n  // call runtime.executePendingJobs() to run any code that was\n  // waiting on the promise or callback.\n  promise.settled.then(vm.runtime.executePendingJobs)\n  return promise.handle\n})\nreadFileHandle.consume((handle) => vm.setProp(vm.global, \"readFile\", handle))\n\n// Evaluate code that uses `readFile`, which returns a promise\nconst result = vm.evalCode(`(async () => {\n  const content = await readFile('example.txt')\n  return content.toUpperCase()\n})()`)\nconst promiseHandle = vm.unwrapResult(result)\n\n// Convert the promise handle into a native promise and await it.\n// If code like this deadlocks, make sure you are calling\n// runtime.executePendingJobs appropriately.\nconst resolvedResult = await vm.resolvePromise(promiseHandle)\npromiseHandle.dispose()\nconst resolvedHandle = vm.unwrapResult(resolvedResult)\nconsole.log(\"Result:\", vm.getString(resolvedHandle))\nresolvedHandle.dispose()\n```\n\n#### Asyncify\n\nSometimes, we want to create a function that's synchronous from the perspective\nof QuickJS, but prefer to implement that function _asynchronously_ in your host\ncode. The most obvious use-case is for EcmaScript module loading. The underlying\nQuickJS C library expects the module loader function to return synchronously,\nbut loading data synchronously in the browser or server is somewhere between \"a\nbad idea\" and \"impossible\". QuickJS also doesn't expose an API to \"pause\" the\nexecution of a runtime, and adding such an API is tricky due to the VM's\nimplementation.\n\nAs a work-around, we provide an alternate build of QuickJS processed by\nEmscripten/Binaryen's [ASYNCIFY](https://emscripten.org/docs/porting/asyncify.html)\ncompiler transform. Here's how Emscripten's documentation describes Asyncify:\n\n> Asyncify lets synchronous C or C++ code interact with asynchronous \\[host] JavaScript. This allows things like:\n>\n> - A synchronous call in C that yields to the event loop, which allows browser events to be handled.\n>\n> - A synchronous call in C that waits for an asynchronous operation in \\[host] JS to complete.\n>\n> Asyncify automatically transforms ... code into a form that can be paused and\n> resumed ..., so that it is asynchronous (hence the name “Asyncify”) even though\n> \\[it is written] in a normal synchronous way.\n\nThis means we can suspend an _entire WebAssembly module_ (which could contain\nmultiple runtimes and contexts) while our host Javascript loads data\nasynchronously, and then resume execution once the data load completes. This is\na very handy superpower, but it comes with a couple of major limitations:\n\n1. _An asyncified WebAssembly module can only suspend to wait for a single\n   asynchronous call at a time_. You may call back into a suspended WebAssembly\n   module eg. to create a QuickJS value to return a result, but the system will\n   crash if this call tries to suspend again. Take a look at Emscripten's documentation\n   on [reentrancy](https://emscripten.org/docs/porting/asyncify.html#reentrancy).\n\n2. _Asyncified code is bigger and runs slower_. The asyncified build of\n   Quickjs-emscripten library is 1M, 2x larger than the 500K of the default\n   version. There may be room for further\n   [optimization](https://emscripten.org/docs/porting/asyncify.html#optimizing)\n   Of our build in the future.\n\nTo use asyncify features, use the following functions:\n\n- [newAsyncRuntime][]: create a runtime inside a new WebAssembly module.\n- [newAsyncContext][]: create runtime and context together inside a new\n  WebAssembly module.\n- [newQuickJSAsyncWASMModule][]: create an empty WebAssembly module.\n\n[newasyncruntime]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newasyncruntime\n[newasynccontext]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newasynccontext\n[newquickjsasyncwasmmodule]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#newquickjsasyncwasmmodule\n\nThese functions are asynchronous because they always create a new underlying\nWebAssembly module so that each instance can suspend and resume independently,\nand instantiating a WebAssembly module is an async operation. This also adds\nsubstantial overhead compared to creating a runtime or context inside an\nexisting module; if you only need to wait for a single async action at a time,\nyou can create a single top-level module and create runtimes or contexts inside\nof it.\n\n##### Async module loader\n\nHere's an example of valuating a script that loads React asynchronously as an ES\nmodule. In our example, we're loading from the filesystem for reproducibility,\nbut you can use this technique to load using `fetch`.\n\n```typescript\nconst module = await newQuickJSAsyncWASMModule()\nconst runtime = module.newRuntime()\nconst path = await import(\"path\")\nconst { promises: fs } = await import(\"fs\")\n\nconst importsPath = path.join(__dirname, \"../examples/imports\") + \"/\"\n// Module loaders can return promises.\n// Execution will suspend until the promise resolves.\nruntime.setModuleLoader((moduleName) => {\n  const modulePath = path.join(importsPath, moduleName)\n  if (!modulePath.startsWith(importsPath)) {\n    throw new Error(\"out of bounds\")\n  }\n  console.log(\"loading\", moduleName, \"from\", modulePath)\n  return fs.readFile(modulePath, \"utf-8\")\n})\n\n// evalCodeAsync is required when execution may suspend.\nconst context = runtime.newContext()\nconst result = await context.evalCodeAsync(`\nimport * as React from 'esm.sh/react@17'\nimport * as ReactDOMServer from 'esm.sh/react-dom@17/server'\nconst e = React.createElement\nglobalThis.html = ReactDOMServer.renderToStaticMarkup(\n  e('div', null, e('strong', null, 'Hello world!'))\n)\n`)\ncontext.unwrapResult(result).dispose()\nconst html = context.getProp(context.global, \"html\").consume(context.getString)\nconsole.log(html) // <div><strong>Hello world!</strong></div>\n```\n\n##### Async on host, sync in QuickJS\n\nHere's an example of turning an async function into a sync function inside the\nVM.\n\n```typescript\nconst context = await newAsyncContext()\nconst path = await import(\"path\")\nconst { promises: fs } = await import(\"fs\")\n\nconst importsPath = path.join(__dirname, \"../examples/imports\") + \"/\"\nconst readFileHandle = context.newAsyncifiedFunction(\"readFile\", async (pathHandle) => {\n  const pathString = path.join(importsPath, context.getString(pathHandle))\n  if (!pathString.startsWith(importsPath)) {\n    throw new Error(\"out of bounds\")\n  }\n  const data = await fs.readFile(pathString, \"utf-8\")\n  return context.newString(data)\n})\nreadFileHandle.consume((fn) => context.setProp(context.global, \"readFile\", fn))\n\n// evalCodeAsync is required when execution may suspend.\nconst result = await context.evalCodeAsync(`\n// Not a promise! Sync! vvvvvvvvvvvvvvvvvvvv \nconst data = JSON.parse(readFile('data.json'))\ndata.map(x => x.toUpperCase()).join(' ')\n`)\nconst upperCaseData = context.unwrapResult(result).consume(context.getString)\nconsole.log(upperCaseData) // 'VERY USEFUL DATA'\n```\n\n### Testing your code\n\nThis library is complicated to use, so please consider automated testing your\nimplementation. We highly writing your test suite to run with both the \"release\"\nbuild variant of quickjs-emscripten, and also the [DEBUG_SYNC] build variant.\nThe debug sync build variant has extra instrumentation code for detecting memory\nleaks.\n\nThe class [TestQuickJSWASMModule] exposes the memory leak detection API, although\nthis API is only accurate when using `DEBUG_SYNC` variant.\n\n```typescript\n// Define your test suite in a function, so that you can test against\n// different module loaders.\nfunction myTests(moduleLoader: () => Promise<QuickJSWASMModule>) {\n  let QuickJS: TestQuickJSWASMModule\n  beforeEach(async () => {\n    // Get a unique TestQuickJSWASMModule instance for each test.\n    const wasmModule = await moduleLoader()\n    QuickJS = new TestQuickJSWASMModule(wasmModule)\n  })\n  afterEach(() => {\n    // Assert that the test disposed all handles. The DEBUG_SYNC build\n    // variant will show detailed traces for each leak.\n    QuickJS.assertNoMemoryAllocated()\n  })\n\n  it(\"works well\", () => {\n    // TODO: write a test using QuickJS\n    const context = QuickJS.newContext()\n    context.unwrapResult(context.evalCode(\"1 + 1\")).dispose()\n    context.dispose()\n  })\n}\n\n// Run the test suite against a matrix of module loaders.\ndescribe(\"Check for memory leaks with QuickJS DEBUG build\", () => {\n  const moduleLoader = memoizePromiseFactory(() => newQuickJSWASMModule(DEBUG_SYNC))\n  myTests(moduleLoader)\n})\n\ndescribe(\"Realistic test with QuickJS RELEASE build\", () => {\n  myTests(getQuickJS)\n})\n```\n\nFor more testing examples, please explore the typescript source of [quickjs-emscripten][ts] repository.\n\n[ts]: https://github.com/justjake/quickjs-emscripten/blob/main/ts\n[debug_sync]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/modules.md#debug_sync\n[testquickjswasmmodule]: https://github.com/justjake/quickjs-emscripten/blob/main/doc/classes/TestQuickJSWASMModule.md\n\n### Debugging\n\n- Switch to a DEBUG build variant of the WebAssembly module to see debug log messages from the C part of this library.\n- Set `process.env.QTS_DEBUG` to see debug log messages from the Javascript part of this library.\n\n### More Documentation\n\n[Github] | [NPM] | [API Documentation][api] | [Examples][tests]\n\n## Background\n\nThis was inspired by seeing https://github.com/maple3142/duktape-eval\n[on Hacker News](https://news.ycombinator.com/item?id=21946565) and Figma's\nblogposts about using building a Javascript plugin runtime:\n\n- [How Figma built the Figma plugin system](https://www.figma.com/blog/how-we-built-the-figma-plugin-system/): Describes the LowLevelJavascriptVm interface.\n- [An update on plugin security](https://www.figma.com/blog/an-update-on-plugin-security/): Figma switches to QuickJS.\n\n## Status & Roadmap\n\n**Stability**: Because the version number of this project is below `1.0.0`,\n\\*expect occasional breaking API changes.\n\n**Security**: This project makes every effort to be secure, but has not been\naudited. Please use with care in production settings.\n\n**Roadmap**: I work on this project in my free time, for fun. Here's I'm\nthinking comes next. Last updated 2022-03-18.\n\n1. Further work on module loading APIs:\n\n   - Create modules via Javascript, instead of source text.\n   - Scan source text for imports, for ahead of time or concurrent loading.\n     (This is possible with third-party tools, so lower priority.)\n\n2. Higher-level tools for reading QuickJS values:\n\n   - Type guard functions: `context.isArray(handle)`, `context.isPromise(handle)`, etc.\n   - Iteration utilities: `context.getIterable(handle)`, `context.iterateObjectEntries(handle)`.\n     This better supports user-level code to deserialize complex handle objects.\n\n3. Higher-level tools for creating QuickJS values:\n\n   - Devise a way to avoid needing to mess around with handles when setting up\n     the environment.\n   - Consider integrating\n     [quickjs-emscripten-sync](https://github.com/reearth/quickjs-emscripten-sync)\n     for automatic translation.\n   - Consider class-based or interface-type-based marshalling.\n\n4. EcmaScript Modules / WebAssembly files / Deno support. This requires me to\n   learn a lot of new things, but should be interesting for modern browser usage.\n\n5. SQLite integration.\n\n## Related\n\n- Duktape wrapped in Wasm: https://github.com/maple3142/duktape-eval/blob/main/src/Makefile\n- QuickJS wrapped in C++: https://github.com/ftk/quickjspp\n\n## Developing\n\nThis library is implemented in two languages: C (compiled to WASM with\nEmscripten), and Typescript.\n\n### The C parts\n\nThe ./c directory contains C code that wraps the QuickJS C library (in ./quickjs).\nPublic functions (those starting with `QTS_`) in ./c/interface.c are\nautomatically exported to native code (via a generated header) and to\nTypescript (via a generated FFI class). See ./generate.ts for how this works.\n\nThe C code builds as both with `emscripten` (using `emcc`), to produce WASM (or\nASM.js) and with `clang`. Build outputs are checked in, so you can iterate on\nthe Javascript parts of the library without setting up the Emscripten toolchain.\n\nIntermediate object files from QuickJS end up in ./build/quickjs/.\n\nThis project uses `emscripten 3.1.32`.\n\n- On ARM64, you should install `emscripten` on your machine. For example on macOS, `brew install emscripten`.\n- If _the correct version of emcc_ is not in your PATH, compilation falls back to using Docker.\n  On ARM64, this is 10-50x slower than native compilation, but it's just fine on x64.\n\nRelated NPM scripts:\n\n- `yarn update-quickjs` will sync the ./quickjs folder with a\n  github repo tracking the upstream QuickJS.\n- `yarn make-debug` will rebuild C outputs into ./build/wrapper\n- `yarn make-release` will rebuild C outputs in release mode, which is the mode\n  that should be checked into the repo.\n\n### The Typescript parts\n\nThe ./ts directory contains Typescript types and wraps the generated Emscripten\nFFI in a more usable interface.\n\nYou'll need `node` and `yarn`. Install dependencies with `yarn install`.\n\n- `yarn build` produces ./dist.\n- `yarn test` runs the tests.\n- `yarn test --watch` watches for changes and re-runs the tests.\n\n### Yarn updates\n\nJust run `yarn set version from sources` to upgrade the Yarn release.\n","_attachments":{},"homepage":"https://github.com/justjake/quickjs-emscripten#readme","bugs":{"url":"https://github.com/justjake/quickjs-emscripten/issues"},"license":"MIT"}