Skip to content

WebAssembly

A guide to using iscc-lib from the browser or Node.js via the @iscc/wasm WebAssembly package. Covers installation, setup for different environments, code generation, streaming, codec operations, and constants.


Installation

npm install @iscc/wasm

Setup

The published package is a single --target web build: an ES module that loads its iscc_wasm_bg.wasm file once at startup. Initialize it before calling any other function. How you initialize depends on your environment.

Bundler (webpack, Vite)

For projects using a JavaScript bundler:

import init, {
    gen_text_code_v0,
    gen_data_code_v0,
    DataHasher,
} from "@iscc/wasm";

// Initialize the WASM module before calling any functions
await init();

const iscc = gen_text_code_v0("Hello World");
console.log(iscc);

Call init() once at application startup.

Browser (native ESM)

For direct use in browsers without a bundler, serve the files of the installed package (node_modules/@iscc/wasm/) and import its entry module:

<script type="module">
 import init, { gen_text_code_v0 } from "./node_modules/@iscc/wasm/iscc_wasm.js";

  await init();
  const iscc = gen_text_code_v0("Hello World");
  document.getElementById("result").textContent = iscc;
</script>

Node.js

Called without an argument, init() fetches the .wasm file by URL, and Node's fetch cannot read file: URLs. Read the file from disk and pass its bytes to initSync() instead:

import {
    readFileSync
} from "node:fs";
import {
    createRequire
} from "node:module";
import {
    initSync,
    gen_text_code_v0
} from "@iscc/wasm";

// Node's fetch cannot read file: URLs, so load the WASM bytes from disk
const require = createRequire(import.meta.url);
initSync({
    module: readFileSync(require.resolve("@iscc/wasm/iscc_wasm_bg.wasm"))
});

const iscc = gen_text_code_v0("Hello World");
console.log(iscc);

Prefer @iscc/lib for Node.js

For Node.js server applications, the native addon @iscc/lib provides better performance than the WASM package. Use @iscc/wasm for Node.js only when native addon installation is not possible (e.g., restricted build environments).

Code generation

Nine of the 10 gen_*_v0 functions return the ISCC code as a string. gen_sum_code_v0 returns a WasmSumCodeResult object with iscc, datahash and filesize fields, plus units when add_units is true (see Sum-Code). Optional parameters use undefined for defaults.

Meta-Code

import {
    gen_meta_code_v0
} from "@iscc/wasm";

const iscc = gen_meta_code_v0("Die Unendliche Geschichte", "Von Michael Ende");
console.log(iscc); // "ISCC:AAA..."

// With structured metadata (JSON string)
const meta = JSON.stringify({
    title: "Example",
    author: "Author"
});
const iscc2 = gen_meta_code_v0("Example Title", undefined, meta);
console.log(iscc2);

Text-Code

import {
    gen_text_code_v0
} from "@iscc/wasm";

const iscc = gen_text_code_v0("Hello World");
console.log(iscc); // "ISCC:EAA..."

Image-Code

import {
    gen_image_code_v0
} from "@iscc/wasm";

// 32x32 grayscale thumbnail as Uint8Array (1024 bytes)
const pixels = new Uint8Array(1024).fill(128);
const iscc = gen_image_code_v0(pixels);
console.log(iscc); // "ISCC:EEA..."

Audio-Code

import {
    gen_audio_code_v0
} from "@iscc/wasm";

// Chromaprint feature vector (signed integers)
const fingerprint = [123456, -789012, 345678, 901234];
const iscc = gen_audio_code_v0(fingerprint);
console.log(iscc); // "ISCC:EIA..."

Video-Code

import {
    gen_video_code_v0
} from "@iscc/wasm";

// MPEG-7 frame signatures: array of arrays of integers
const frameSigs = [new Array(380).fill(0), new Array(380).fill(1)];
const iscc = gen_video_code_v0(frameSigs);
console.log(iscc); // "ISCC:EMA..."

Mixed-Code

import {
    gen_text_code_v0,
    gen_image_code_v0,
    gen_mixed_code_v0
} from "@iscc/wasm";

const textCode = gen_text_code_v0("Hello World");
const imageCode = gen_image_code_v0(new Uint8Array(1024).fill(128));
const iscc = gen_mixed_code_v0([textCode, imageCode]);
console.log(iscc); // "ISCC:EQA..."

Data-Code

import {
    gen_data_code_v0
} from "@iscc/wasm";

const encoder = new TextEncoder();
const data = encoder.encode("Hello World".repeat(1000));
const iscc = gen_data_code_v0(data);
console.log(iscc); // "ISCC:GAA..."

Instance-Code

import {
    gen_instance_code_v0
} from "@iscc/wasm";

const encoder = new TextEncoder();
const data = encoder.encode("Hello World");
const iscc = gen_instance_code_v0(data);
console.log(iscc); // "ISCC:IAA..."

ISCC-CODE

import {
    gen_data_code_v0,
    gen_instance_code_v0,
    gen_iscc_code_v0
} from "@iscc/wasm";

const encoder = new TextEncoder();
const data = encoder.encode("Hello World".repeat(1000));
const dataCode = gen_data_code_v0(data);
const instanceCode = gen_instance_code_v0(data);
const iscc = gen_iscc_code_v0([dataCode, instanceCode]);
console.log(iscc); // "ISCC:KUA..."

Sum-Code

Generate a composite ISCC-CODE from raw bytes in a single pass. The WASM package operates on in-memory data (Uint8Array) instead of file paths since there is no filesystem access in the browser:

import {
    gen_sum_code_v0
} from "@iscc/wasm";

const encoder = new TextEncoder();
const data = encoder.encode("Hello World".repeat(1000));
const result = gen_sum_code_v0(data);
console.log(result.iscc); // "ISCC:KUA..."
console.log(result.datahash); // Multihash of the data
console.log(result.filesize); // Size in bytes

Binary data

WASM uses Uint8Array for binary data (not Node.js Buffer). When working with files in the browser, convert File or Blob objects to Uint8Array:

import {
    gen_data_code_v0
} from "@iscc/wasm";

// From a File input element
const file = document.getElementById("fileInput").files[0];
const arrayBuffer = await file.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
const iscc = gen_data_code_v0(data);

When working with fetch responses:

const response = await fetch("https://example.com/document.pdf");
const buffer = await response.arrayBuffer();
const data = new Uint8Array(buffer);
const iscc = gen_data_code_v0(data);

Streaming

For large files, use DataHasher and InstanceHasher to process data in chunks.

DataHasher

import {
    DataHasher
} from "@iscc/wasm";

const hasher = new DataHasher();

// Process file in chunks (e.g., from a ReadableStream)
const response = await fetch("https://example.com/large_file.bin");
const reader = response.body.getReader();

while (true) {
    const {
        done,
        value
    } = await reader.read();
    if (done) break;
    hasher.update(value); // value is a Uint8Array
}

const iscc = hasher.finalize();
console.log(iscc);

InstanceHasher

import {
    InstanceHasher
} from "@iscc/wasm";

const hasher = new InstanceHasher();

// Process data in chunks
hasher.update(new Uint8Array([1, 2, 3]));
hasher.update(new Uint8Array([4, 5, 6]));

const iscc = hasher.finalize();
console.log(iscc);

SumHasher

Produce a composite ISCC-CODE (Data-Code + Instance-Code) from a chunked stream in a single pass, without running two separate hashers. finalize() returns a WasmSumCodeResult with iscc, datahash, filesize, and optional units fields — the same shape as gen_sum_code_v0:

import {
    SumHasher
} from "@iscc/wasm";

const hasher = new SumHasher();

// Process file in chunks (e.g., from a ReadableStream)
const response = await fetch("https://example.com/large_file.bin");
const reader = response.body.getReader();

while (true) {
    const {
        done,
        value
    } = await reader.read();
    if (done) break;
    hasher.update(value); // value is a Uint8Array
}

// finalize(bits?, wide?, add_units?) — pass add_units=true to include units
const result = hasher.finalize(undefined, undefined, true);
console.log(result.iscc); // "ISCC:KUA..."
console.log(result.datahash); // Multihash of the data
console.log(result.filesize); // Size in bytes
console.log(result.units); // [dataCode, instanceCode]

All three hashers accept Uint8Array input. Each is single-use: the first finalize() call consumes the hasher, even when it fails (for example on an invalid bits value). After that, further calls throw an error.

Text utilities

Text normalization functions are available for preprocessing:

import {
    text_clean,
    text_collapse,
    text_remove_newlines,
    text_trim
} from "@iscc/wasm";

// Normalize text for display
const cleaned = text_clean("  Hello\r\n\r\n\r\nWorld  ");

// Simplify text for similarity hashing
const collapsed = text_collapse("Hello, World!");

// Remove newlines, collapse whitespace
const singleLine = text_remove_newlines("Hello\nWorld");

// Trim to UTF-8 byte limit
const trimmed = text_trim("Hello World", 5);

Codec operations

Functions for encoding, decoding, and decomposing ISCC codes. These operate on the ISCC binary format defined in ISO 24138.

Encode and decode

Construct an ISCC unit from raw header fields and digest, then decode it back:

import {
    encode_component,
    iscc_decode
} from "@iscc/wasm";

// Encode: maintype=0 (Meta), subtype=0, version=0, 64 bits, 8-byte digest
const digest = new Uint8Array([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]);
const code = encode_component(0, 0, 0, 64, digest);
console.log(code); // ISCC unit string (without "ISCC:" prefix)

// Decode: parse an ISCC unit string back into header components and digest
const result = iscc_decode(code);
console.log(`Maintype: ${result.maintype}, Subtype: ${result.subtype}`);
console.log(`Version: ${result.version}, Length: ${result.length}`);
console.log(`Digest:`, result.digest);

iscc_decode returns an IsccDecodeResult object with maintype, subtype, version, length (length index), and digest (Uint8Array) fields.

ISCC-IDv1 (experimental)

Mint an ISCC-IDv1 from a microsecond UTC timestamp and a HUB-ID. The timestamp occupies the high 52 bits and the HUB-ID the low 12 bits; realm (0 = testnet, 1 = mainnet) becomes the SubType.

Experimental

ISCC-IDv1 is not part of ISO 24138 and may change in a minor release.

import {
    gen_iscc_id_v1,
    iscc_decode
} from "@iscc/wasm";

const iscc = gen_iscc_id_v1(1751831876325218, 1, 0);
console.log(iscc); // "ISCC:MAIGHFECJMOPMIAB"

// There is no dedicated decoder — recover the fields with iscc_decode and bit math:
const d = iscc_decode(iscc);
let n = 0n;
for (let i = 0; i < 8; i++) n = (n << 8n) | BigInt(d.digest[i]);
const timestamp = n >> 12n; // 1751831876325218n
const hubId = n & 0xfffn; // 1n
const realm = d.subtype; // 0
console.log(d.version === 1); // true (ISCC-IDv1)

Decompose

Split a composite ISCC-CODE into its individual unit codes:

import {
    gen_data_code_v0,
    gen_instance_code_v0,
    gen_iscc_code_v0,
    iscc_decompose
} from "@iscc/wasm";

const encoder = new TextEncoder();
const data = encoder.encode("Hello World".repeat(1000));
const dataCode = gen_data_code_v0(data);
const instanceCode = gen_instance_code_v0(data);
const isccCode = gen_iscc_code_v0([dataCode, instanceCode]);

// Decompose into individual units
const units = iscc_decompose(isccCode);
for (const unit of units) {
    console.log(unit); // Each unit code (without "ISCC:" prefix)
}

ISCC-SEQ

encode_seq(units) packs an ordered list of ISCC-UNITs into an ISCC-SEQ byte string (IEP-0020) and returns a Uint8Array with the header and body bytes of each unit, in the given order. units may be an array or any other iterable of strings. decode_seq(data: Uint8Array): string[] reads one back into ISCC:-prefixed unit strings. Base32 input is strict (no padding, zero spare bits) and upper-casing is ASCII-only. ISCC-CODE, ISCC-ID and ISCC-FLAKE units are rejected.

import {
    decode_seq,
    encode_seq
} from "@iscc/wasm";

const data = encode_seq(["ISCC:EAD2RASIYU5IKLENP2OFI4CHZGRWYQCSW2WKX3Y6FJGOCXSYNYGLGBI"]);
console.log(data.length); // 34
console.log(Array.from(data.subarray(0, 6), (b) => b.toString(16).padStart(2, "0")).join(""));
// "2007a88248c5"

const units = decode_seq(data);
console.log(units); // ["ISCC:EAD2RASIYU5IKLENP2OFI4CHZGRWYQCSW2WKX3Y6FJGOCXSYNYGLGBI"]

// The round trip is defined on bytes: encode_seq(decode_seq(data)) equals data
const again = encode_seq(units);
console.log(again.length === data.length && again.every((b, i) => b === data[i])); // true

Other codec functions

  • encode_base64(data) — encode a Uint8Array to base64 string
  • json_to_data_url(json) — convert a JSON string to a data:application/json;base64,... URL
  • soft_hash_video_v0(frameSigs, bits?) — compute a video similarity hash from MPEG-7 frame signatures, returns Uint8Array

Algorithm primitives

Low-level algorithm functions are available for advanced use cases:

import {
    sliding_window
} from "@iscc/wasm";

// Sliding window: overlapping substrings of width Unicode characters
const windows = sliding_window("Hello World", 4);
// ["Hell", "ello", "llo ", "lo W", "o Wo", " Wor", "Worl", "orld"]

Additional primitives:

  • alg_simhash(hashDigests) — compute a SimHash digest from an array of equal-length Uint8Arrays, returns Uint8Array
  • alg_minhash_256(features) — compute a 256-bit MinHash digest from 32-bit integer features, returns Uint8Array; throws on an empty array
  • alg_cdc_chunks(data, utf32, avgChunkSize?) — split data into content-defined chunks (default average chunk size 1024), returns an array of Uint8Array chunks

Constants

Constants are exposed as getter functions (uppercase names matching other bindings):

import {
    META_TRIM_NAME,
    META_TRIM_DESCRIPTION,
    META_TRIM_META,
    IO_READ_SIZE,
    TEXT_NGRAM_SIZE,
} from "@iscc/wasm";

META_TRIM_NAME(); // 128 — max byte length for name normalization
META_TRIM_DESCRIPTION(); // 4096 — max byte length for description normalization
META_TRIM_META(); // 128_000 — max decoded payload size in bytes for the meta element
IO_READ_SIZE(); // 4_194_304 — default read buffer size (4 MB)
TEXT_NGRAM_SIZE(); // 13 — n-gram size for text similarity hashing

Conformance testing

Verify the library against official test vectors:

import {
    conformance_selftest
} from "@iscc/wasm";

console.log(conformance_selftest()); // true

Error handling

Functions throw on invalid input. Every number argument must be an integer within the range of its parameter (for example, bits and nbytes must lie in 0 to 2^32 − 1 and each gen_audio_code_v0 feature in the signed 32-bit range). A negative, fractional, non-finite or too large number throws an error that names the parameter, for example Invalid bits: -1.

Number and boolean arguments are type-checked, not converted. A value that is not a number where a number is expected throws Invalid <name>: expected a number: null for a required number, a numeric string such as "2", or a boolean. This applies to every element of a number array too (Invalid cv[1]: expected a number). For an optional number such as bits, null and undefined both select the default. Boolean flags (wide, add_units, utf32) must be true or false. Any other value, such as the string "false" or 0, throws Invalid <name>: expected a boolean, and null or undefined select the default of an optional flag.

Number-array parameters (cv, features) accept arrays, typed arrays such as Int32Array, and array-like objects with a length. An iterable without a length, such as a Set or a generator, throws Invalid <name>.length: expected a number. Convert it first with Array.from. An exception thrown while the array is read, for example by a getter, comes back as an error that names the parameter.

Byte and string parameters are not type-checked: the generated JavaScript glue converts them before the library runs. Where bytes are expected, pass a Uint8Array (a Node.js Buffer is one). A string or a plain array is converted without an error and gives a different, valid code: gen_data_code_v0("abc") returns the code of three zero bytes, not of the text, and gen_data_code_v0([1, "2", null, 300]) the code of the bytes 1, 2, 0 and 44. Where a string is expected, a number or another non-string value throws RuntimeError: memory access out of bounds instead of an error that names the parameter. The TypeScript declarations reject both mistakes; plain JavaScript callers should check the types before the call.

Wrap calls in try/catch to handle invalid input:

import {
    gen_text_code_v0
} from "@iscc/wasm";

try {
    gen_text_code_v0("Hello", 13); // bits must be a multiple of 32 from 32 to 256
} catch (error) {
    console.error(`Invalid input: ${error.message}`);
}