{"id":13567159,"url":"https://github.com/torch2424/as-bind","last_synced_at":"2025-10-12T15:10:09.214Z","repository":{"id":37852440,"uuid":"204398125","full_name":"torch2424/as-bind","owner":"torch2424","description":"Isomorphic library to handle passing high-level data structures between AssemblyScript and JavaScript 🤝🚀","archived":false,"fork":false,"pushed_at":"2024-01-21T09:47:18.000Z","size":7982,"stargazers_count":236,"open_issues_count":36,"forks_count":24,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-04-14T07:55:26.887Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://torch2424.github.io/as-bind/","language":"WebAssembly","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/torch2424.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-08-26T04:50:39.000Z","updated_at":"2024-06-18T15:37:24.330Z","dependencies_parsed_at":"2024-06-18T15:37:13.187Z","dependency_job_id":"240006fe-c7bb-4d8b-bad3-2b2fb7d23b12","html_url":"https://github.com/torch2424/as-bind","commit_stats":null,"previous_names":[],"tags_count":37,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torch2424%2Fas-bind","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torch2424%2Fas-bind/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torch2424%2Fas-bind/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/torch2424%2Fas-bind/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/torch2424","download_url":"https://codeload.github.com/torch2424/as-bind/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247261612,"owners_count":20910108,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T13:02:25.048Z","updated_at":"2025-10-12T15:10:09.157Z","avatar_url":"https://github.com/torch2424.png","language":"WebAssembly","funding_links":[],"categories":["WebAssembly"],"sub_categories":[],"readme":"# as-bind\n\n\u003c!-- Badges --\u003e\n\n[![Build Status](https://travis-ci.org/torch2424/as-bind.svg?branch=master)](https://travis-ci.org/torch2424/as-bind)\n![npm bundle size (minified)](https://img.shields.io/bundlephobia/min/as-bind.svg)\n![npm](https://img.shields.io/npm/dt/as-bind.svg)\n![npm version](https://img.shields.io/npm/v/as-bind.svg)\n![GitHub](https://img.shields.io/github/license/torch2424/as-bind.svg)\n\nIsomorphic library to handle passing high-level data structures between AssemblyScript and JavaScript. 🤝🚀\n\n[Markdown Parser Demo](https://torch2424.github.io/as-bind/)\n\n![Asbind Markdown Parser Demo Gif](./assets/asbind.gif)\n\n## Table of Contents\n\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Additional Examples](#additional-examples)\n- [Supported Data Types](#supported-data-types)\n- [Supported AssemblyScript Runtime Variants](#supported-assemblyscript-runtime-variants)\n- [Reference API](#reference-api)\n- [Motivation](#motivation)\n- [Performance](#performance)\n- [Production](#production)\n- [Projects using as-bind](#projects-using-as-bind)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Features\n\n- The library is isomorphic. Meaning it supports both the Browser, and Node! And has ESM, AMD, CommonJS, and IIFE bundles! 🌐\n- Wraps around the [AssemblyScript Loader](https://github.com/AssemblyScript/assemblyscript/tree/master/lib/loader). The loader handles all the heavy-lifting of passing data into WebAssembly linear memory. 💪\n- Wraps around imported JavaScript functions, and exported AssemblyScript functions of the AssemblyScript Wasm Module. This allows high-level data types to be passed directly to exported AssemblyScript functions! 🤯\n- Moves a lot of work to compile-time using [AssemblyScript Transforms](https://www.assemblyscript.org/transforms.html#transforms) and completely avoids module-specific “glue code”. 🏃\n- Installable from package managers (npm), with a modern JavaScript API syntax. 📦\n- The library is [\u003c 4KB (minified and gzip'd)](https://bundlephobia.com/result?p=as-bind), _including_ the AssemblyScript Loader ! 🌲\n- This library is currently (as of January, 2020) the [wasm-bindgen](https://github.com/rustwasm/wasm-bindgen) of AssemblyScript. 😀\n\n## Installation\n\nYou can install as-bind in your project by running the following:\n\n`npm install --save as-bind`\n\n## Quick Start\n\n**1. Compiling your Assemblyscript**\n\nTo enable as-bind for your AssemblyScript Wasm modules, add the as-bind transform when compiling your module:\n\n`asc your-entryfile.ts --exportRuntime --transform as-bind [...other cli options...]`\n\nThe things to notice are:\n\n- `--transform as-bind` - This is the as-bind transform that runs at compile time. It embeds all the required type information into the WebAssembly Module.\n- `--exportRuntime` - This is required for the AssemblyScript Loader to work properly. It [exposes functions](https://www.assemblyscript.org/garbage-collection.html#runtime-interface) on the module to allocate memory from JavaScript.\n\nFor **optional testing purposes** , let's export an example function we can try in `your-entryfile.ts`:\n\n```typescript\nexport function myExportedFunctionThatTakesAString(value: string): string {\n  return \"AsBind: \" + value;\n}\n```\n\n**2. In your Javascript**\n\nFor **browser** JavaScript. We can do the following:\n\n```javascript\n// If you are using a Javascript bundler, use the ESM bundle with import syntax\nimport * as AsBind from \"as-bind\";\n\n// If you are not using a bundler add a \u003cscript\u003e tag to your HTML\n// Where the `src` points to the iife bundle (as-bind.iife.js), for example: https://unpkg.com/as-bind\n// Then, INSTEAD of using the import syntax, do: `const { AsBind } = AsBindIIFE;`\n\nconst wasm = fetch(\"./path-to-my-wasm.wasm\");\n\nconst asyncTask = async () =\u003e {\n  const asBindInstance = await AsBind.instantiate(wasm);\n\n  // You can now use your wasm / as-bind instance!\n  const response = asBindInstance.exports.myExportedFunctionThatTakesAString(\n    \"Hello World!\"\n  );\n  console.log(response); // AsBind: Hello World!\n};\nasyncTask();\n```\n\nFor **Node** JavaScript, we would use the CommonJS bundle by doing the following:\n\n```javascript\n// We need to import the direct as-bind.cjs.js for Node applications.\n// This is because the default \"main\" key in the `package.json`,\n// is the as-bind transform script\nconst AsBind = require(\"as-bind/dist/as-bind.cjs.js\");\n\nconst fs = require(\"fs\");\n\nconst wasm = fs.readFileSync(\"./path-to-my-wasm.wasm\");\n\nconst asyncTask = async () =\u003e {\n  const asBindInstance = await AsBind.instantiate(wasm);\n\n  // You can now use your wasm / as-bind instance!\n  const response = asBindInstance.exports.myExportedFunctionThatTakesAString(\n    \"Hello World!\"\n  );\n  console.log(response); // AsBind: Hello World!\n};\nasyncTask();\n```\n\n## Additional Examples\n\n## Passing a high-level type to a an exported function, and returning a high-level type\n\n[See the Quick Start](#quick-start)\n\n## Passing a high-level type to an imported function\n\nIn this example, we will implement a `console.log` that we can call from AssemblyScript!\n\n**AssemblyScript**\n\nInside of `myWasmFileName.ts`:\n\n```typescript\ndeclare function consoleLog(message: string): void;\n\nexport function myExportedFunctionThatWillCallConsoleLog(): void {\n  consoleLog(\"Hello from AS!\");\n}\n```\n\n**JavaScript**\n\n```javascript\nimport { AsBind } from \"as-bind\";\n\nconst wasm = fetch(\"./path-to-my-wasm.wasm\");\n\nconst asyncTask = async () =\u003e {\n  // Instantiate the wasm file, and pass in our importObject\n  const asBindInstance = await AsBind.instantiate(wasm, {\n    myWasmFileName: {\n      consoleLog: message =\u003e {\n        console.log(message);\n      }\n    }\n  });\n\n  // Should call consoleLog, and log: \"Hello from AS!\"\n  asBindInstance.exports.myExportedFunctionThatWillCallConsoleLog();\n};\nasyncTask();\n```\n\n## Supported Data Types\n\nAll primitive types, ie. Numbers (`u8`, `f32`, ...) , Strings, Typed Arrays (`Uint8Array`, `Float32Array`, ...) are supported. All of those types can also be used with `Array\u003cT\u003e`.\n\nCustom classes are currently not support, but planned.\n\n## Browser SDK\n\nas-bind works with the Browser SDK. For a fully working example, see the [`browser-sdk` example](/torch2424/as-bind/tree/master/examples/browser-sdk).\n\n## Reference API\n\n### AsBind\n\nThe default exported ESM class of `as-bind`, also available as `import { AsBind } from \"as-bind\"` / `const { AsBind } = require('as-bind')`.\n\n#### Class Properties\n\nThe `AsBind` class is meant to _vaguely_ act as the [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly) Object exposed to JavaScript environments.\n\n##### version\n\n`AsBind.version: string`\n\nValue that is the current version of your imported AsBind.\n\n##### instantiate\n\n```typescript\nAsBind.instantiate: (\n  moduleOrBuffer: (\n    WebAssembly.Module |\n    BufferSource |\n    Response |\n    PromiseLike\u003cWebAssembly.Module\u003e\n  ),\n  imports?: WasmImports\n) =\u003e Promise\u003cAsBindInstance\u003e`\n```\n\nThis function is the equivalent to the [AssemblyScript Loader instantiate](https://github.com/AssemblyScript/assemblyscript/tree/master/lib/loader#api) function, which is similar to the [WebAssembly.instantiateStreaming](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/WebAssembly/instantiateStreaming) function. It essentially takes as its parameters:\n\n- Any type of object that can be (resolved) and instantied into a WebAssembly instance. Which in our case would be an AsBindInstance.\n\n- A [WebAssembly importObject](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/WebAssembly/instantiateStreaming), which would have all of your imported functions that can be called from within your AssemblyScript module.\n\n##### instantiateSync\n\n```typescript\nAsBind.instantiateSync: (\n  moduleOrBuffer: (\n    WebAssembly.Module |\n    BufferSource\n  ),\n  imports?: WasmImports\n) =\u003e AsBindInstance`\n```\n\nThis is a synchronous version of `AsBind.instantiate`. This does not accept a promise-like as its module, and returns an AsBindInstance instead of a Promise that resolves an AsBindInstance. **This is only reccomended for use in testing or development**. Please see the Documentation sections for `AsBind.instantiate` for more information.\n\n#### Instance Properties\n\nAn AsBindInstance is vaguely similar to a [WebAssembly instance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance).\n\n##### loadedModule\n\nThe raw, untouched instance of the WebAssembly Module.\n\n##### exports\n\nSimilar to to [WebAssembly.Instance.prototype.exports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/exports), this is an object containing all of the exported fields from the WebAssembly module. However, **exported functions** are bound / wrapped in which they will handle passing the supported high-level data types to the exported AssemblyScript function.\n\n##### importObject\n\nSimilar to to [WebAssembly.instantiateStreaming() importObject](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming), this is the augmented `importObject`. It’s based on the original that was passed to one of the instantiation functions, but functions have been wrapped to handle high-level types.\n\n## Motivation\n\nThis library was inspired by several chats I had with some awesome buddies of mine in the WebAssembly Community:\n\n- [Till Schneidereit](https://twitter.com/tschneidereit) and I had a chat about [WasmBoy](https://github.com/torch2424/wasmboy), and about how I had a really good experience writing the emulator, even though I had to do my own memory management. But they helped me realize, building something low level isn't that bad with manual memory management, but building something like a markdown parser would be very tedious since you have to manually write the string back and forth. Which then inspired this library, and its [markdown parser demo](https://torch2424.github.io/as-bind/).\n\n- While I was building [WasmByExample](https://wasmbyexample.dev/?programmingLanguage=assemblyscript) I wanted to start building the \"High Level Data Structures\" section. I then realized how much work it would be to maintain code for passing data between WebAssembly Linear memory would be for each data type, and how much work it would be to created each individual example. Then, my buddy [Ashley Williams](https://twitter.com/ag_dubs) helped me realize, if your docs are becoming too complex, it may be a good idea to write a tool. That way you have less docs to write, and users will have an easier time using your stuff!\n\nThus, this library was made to help AssemblyScript/JavaScript users build awesome things! I also want to give a huge thanks to the [AssemblyScript team](https://github.com/AssemblyScript/meta) and community for the help they provided me. I'm super appreciative of you all! 😄🎉\n\n(Also! Huge Shoutout to @surma for doing the awesome refactor to use AssemblyScript compiler transforms! 🙏)\n\n## Performance\n\n**TL;DR** This library should be pretty darn fast. 🤔\n\nThe transform embeds all the required type information of imported and exported functions into a custom section of the WebAssembly module. All the runtime does is utilize the AssemblyScript Loader to convert these types from JS to ASC and vice-versa. Apart from `Array\u003cT\u003e`, which needs to be handled recursively, the overhead is fairly static and minimal.\n\nIn the future, these types of high-level data passing tools might not be needed at all, as the [WebAssembly Inteface Types proposal](https://github.com/WebAssembly/interface-types/blob/master/proposals/interface-types/Explainer.md) aims to give WebAssembly an understanding of higher-level types.\n\n## Projects using as-bind\n\n- The as-bind example is a Markdown Parser, in which as-bind takes in a string, passes it to a rough markdown parser / compiler written in AssemblyScript, and returns a string. [(Live Demo)](https://torch2424.github.io/as-bind/), [(Source Code)](https://github.com/torch2424/as-bind/tree/master/examples/markdown-parser)\n\n- [use-as-bind](https://github.com/tylervipond/use-as-bind) is a React hook for using as-bind with an as-bind enabled WASM source. It's goal is to provide a simple API for React users to add WASM to their apps. [(Live Demo)](https://tylervipond.github.io/use-as-bind/)\n\n- [as-loader](https://github.com/piotr-oles/as-loader) is a [webpack](https://webpack.js.org/) loader for AssemblyScript with built-in as-bind support.\n\n_If you're project is using as-bind, and you would like to be featured here. Please open a README with links to your project, and if appropriate, explaining how as-bind is being used._ 😊\n\n## Contributing\n\nContributions are definitely welcome! Feel free to open a PR for small fixes such as typos and things. Larger fixes, or new features should start out as an issue for discussion, in which then a PR should be made. 🥳\n\nThis project will also adhere to the [AssemblyScript Code of Conduct](https://github.com/AssemblyScript/assemblyscript/blob/master/CODE_OF_CONDUCT.md).\n\n## License\n\n[MIT](https://oss.ninja/mit/torch2424). 📝\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftorch2424%2Fas-bind","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftorch2424%2Fas-bind","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftorch2424%2Fas-bind/lists"}