Skip to content

WASM Quickstart

The npm package exports an async initializer plus the TypeScript-facing classes and functions generated by wasm-bindgen. Initialize the module once before constructing frames or parsing molecular data.

1. Install and Initialize

npm install @molcrafts/molrs
import init, { generate3D, parseSMILES, writeFrame } from "@molcrafts/molrs";

await init();

init() loads and initializes the WebAssembly module. Call it once near the start of your application. After that, exported functions and classes are ready to use.

2. Parse, Embed, and Export

const ir = parseSMILES("CCO");
const frame2d = ir.toFrame();
const frame3d = generate3D(frame2d, "fast", 42);

console.log(writeFrame(frame3d, "xyz"));

The API shape mirrors Python, but uses JavaScript naming conventions: parse_smiles becomes parseSMILES, and to_frame becomes toFrame. Generated TypeScript declarations in pkg/molrs.d.ts are the source of truth for exported names.

3. Inspect Columns

Frames contain blocks, and blocks contain typed columns. The following example reads coordinate arrays from the atoms block:

const atoms = frame3d.getBlock("atoms");
if (!atoms) throw new Error("missing atoms block");

const x = atoms.copyColF("x");
const y = atoms.copyColF("y");
const z = atoms.copyColF("z");

console.log(atoms.nrows(), x[0], y[0], z[0]);

copyColF returns an owned typed-array copy that is safe to store. View-style accessors expose WebAssembly memory and are useful for performance-sensitive code, but the view can be invalidated by later allocations. Prefer copies until profiling proves the extra transfer matters.

4. Build from Source

The docs and npm publish pipeline use the same bundler target:

cd molrs-wasm
wasm-pack build --release --target bundler --scope molcrafts --out-name molrs

This writes molrs-wasm/pkg/. That directory is generated and ignored by git. Applications can link it locally during development:

{
  "dependencies": {
    "@molcrafts/molrs": "link:../molrs-wasm/pkg"
  }
}

5. Variant Builds

The WebAssembly API favors explicit data movement. Numeric arrays cross the boundary as typed arrays, and large columns can be viewed through the module's linear memory when the API exposes a pointer. For application code, copying columns with helpers such as copyColF is simpler and avoids lifetime mistakes.

Default npm builds include SMILES, I/O, compute, and embed support. Smaller local builds can disable default Cargo features, but a page should only load one variant of the package at a time because each WebAssembly module owns a distinct JavaScript class identity.