GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — wasm-split-tool/runtime at main · AnranS/wasm-split-tool

Expand file tree

/

runtime

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

runtime

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
src
src
 
 
test
test
 
 
.gitignore
.gitignore
 
 
.npmignore
.npmignore
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
README.zh-CN.md
README.zh-CN.md
 
 
package-lock.json
package-lock.json
 
 
package.json
package.json
 
 
tsconfig.json
tsconfig.json
 
 
tsup.config.ts
tsup.config.ts
 
 
vitest.config.ts
vitest.config.ts
 
 

README.md

Outline

@wasm-split/runtime

English · 简体中文

Browser runtime for the wasm-split toolchain — the Rust CLI lives in the parent directory of this package inside the same repo, and emits either a primary.wasm + secondary.wasm pair (split mode) or a primary.archive.wasm + func_archive.bin pair (archive mode). This package consumes both.

wasm-split supports two split modes; this runtime handles both:

  • split mode — slice a .wasm into a hot primary that boots immediately plus a cold secondary fetched lazily. Both modules share memory / table / globals. The runtime provides the trampoline imports primary expects, fetches secondary, and instantiates it against primary's instance.
  • archive mode (wasmcode2, for iOS WKWebView) — slice a .wasm into a primary plus a func_archive.bin archive (verbatim Type/Import sections + per-cold-function body bytes, optionally Brotli-compressed per entry). The runtime does not instantiate the archive as one module — it assembles a micro-module per cold batch on demand, instantiates it, and uses an active elem segment to overwrite trampolines in the shared table. JSC never sees the whole cold set, so the iOS memory spike disappears.

Install

npm install @wasm-split/runtime

ESM-first, ships CJS too. Browser-only (uses WebAssembly.instantiateStreaming, fetch, etc.). Node 18+ also works for testing.

Typing your exports

WasmSplitLoader is generic — declare your wasm module's public surface once and every call site narrows to it:

// exports.d.ts — co-locate with the rest of your wasm glue code.
export interface MyExports extends WebAssembly.Exports {
  // `WebAssembly.Exports` is `Record<string, ExportValue>`, so you need
  // to spell out the shapes yourself. Function signatures below are the
  // *JS-side* view — not the raw wasm type.

  // Hot path — available synchronously after `instantiate()` returns.
  bootstrap(): void;
  frame_step(dt: number): void;

  // Cold path — only safe to call after `await inst.secondaryReady`.
  openPlayerInventory(seed: number): number;

  // Shared memory / table / globals re-exported by primary.
  memory: WebAssembly.Memory;
  __indirect_function_table: WebAssembly.Table;
}
import { WasmSplitLoader } from '@wasm-split/runtime';
import type { MyExports } from './exports';

const loader = new WasmSplitLoader<MyExports>({ /* ... */ });
const inst = await loader.instantiate();
// inst.exports is MyExports; TS now catches typos + wrong arity at
// compile time instead of at wasm trap time.

If you don't care about types, drop the generic — inst.exports defaults to WebAssembly.Exports.

Quick start (split mode)

import { WasmSplitLoader } from '@wasm-split/runtime';

// Split manifest must be a parsed object: the loader constructor
// validates `schema_version` synchronously so mismatches fail fast.
const manifest = await fetch('/dist/split-manifest.json').then((r) => r.json());

const loader = new WasmSplitLoader<MyExports>({
  primary:   '/dist/primary.wasm',
  secondary: '/dist/secondary.wasm',
  manifest,
  strategy: 'eager', // see "Loading strategies" below
  imports: {
    env: {
      // ...your existing env imports for the original wasm
    },
  },
});

const inst = await loader.instantiate();
// `inst` is a discriminated union on `mode`: here it narrows to 'split'.
if (inst.mode !== 'split') throw new Error('unreachable');

// Hot path is callable immediately.
inst.exports.bootstrap();

// Gate cold UI on `secondaryReady` — calling cold paths before this throws
// `SecondaryNotReadyError`. (Browsers can't block sync wasm calls on async
// fetch, so this can't be auto-recovered.)
await inst.secondaryReady;
inst.exports.openPlayerInventory();

Quick start (archive mode / iOS optimized)

Swap secondary + manifest for a single archive option — the outward-facing surface (exports, secondaryReady) is unchanged:

import { WasmSplitLoader } from '@wasm-split/runtime';

const archiveManifest = await fetch('/dist/archive-manifest.json').then((r) =>
  r.json(),
);

const loader = new WasmSplitLoader<MyExports>({
  primary: '/dist/primary.archive.wasm',
  archive: {
    source:         '/dist/func_archive.bin',    // WSAR archive bytes
    manifest:       archiveManifest,             // parsed archive-manifest.json
    trampolineFill: 'eager',                     // 'eager' | 'incremental' | 'manual'
    // With Brotli on (default) and iOS < 17 (no DecompressionStream('br')),
    // plug in a sync Brotli decoder:
    // decompressBrotli: (bytes, uncompressedSize) => myBrotli.decode(bytes),
  },
  imports: { env: { /* ... */ } },
  onColdHit: (ev) => {
    // ev is a discriminated union — narrow on `ev.mode` to get the
    // archive-only / split-only fields.
    if (ev.mode === 'archive') telemetry.coldArchiveHit(ev.tableId);
  },
});

const inst = await loader.instantiate();
if (inst.mode !== 'archive') throw new Error('unreachable');

await inst.secondaryReady;                // trampolines have been installed
inst.exports.call_cold_a(5);              // sync: inject batch → run → return

// Advanced: drop an injected batch (releases its WebAssembly.Instance).
// `evictByTableIndex` returns a boolean.
inst.archive.evictByTableIndex(1);

Key facts:

  • secondaryReady in archive mode means "trampolines have been installed per trampolineFill", not "cold functions are instantiated". Cold functions are compiled synchronously on first call.
  • archive is a WasmArchiveLoader instance exposing low-level APIs — injectByTableIndex(slot) (async) / injectByTableIndexSync(slot) / evictByTableIndex(slot) / fillTableWithTrampolines() — for warm-up or manual memory control.
  • archive.manifest must already be a parsed object (ArchiveManifest). The constructor validates schema_version synchronously; pass bytes / URLs yourself if you need to fetch them.
  • The archive and split options are mutually exclusive and validated by the constructor — passing both throws immediately.

trampolineFill

strategy behaviour use when
eager (default) All cold slots get trampolines synchronously inside instantiate() Simple, predictable
incremental Per-type-group fill, yielding to the event loop between groups Low-end iOS: compiling ~100 trampolines in one shot can blow a frame budget
manual Never fills; caller drives archive.fillTableWithTrampolines() / archive.injectByTableIndex() Fine-grained warm-up (only pre-compile one code path)

Loading strategies

strategy controls when secondary is fetched + instantiated. All three strategies share the same secondaryReady / loadSecondary() surface, so you can switch between them without changing call sites.

strategy when secondary loads cold call before ready
eager (default) in parallel with primary instantiation throws SecondaryNotReadyError
lazy only when you explicitly call loadSecondary() throws SecondaryNotReadyError
on-demand the first cold stub auto-kicks loadSecondary() in the background throws SecondaryNotReadyError for the offending call; subsequent calls succeed after await secondaryReady

Using your own preload pipeline

The secondary option accepts more than a URL — anything "bytes-shaped" or WebAssembly.Module-shaped works, including Promises and thunks. That way the host-side prefetch (route-based, idle-callback, <link rel=prefetch>, service worker, etc.) can hand the loader whatever shape it already has without re-fetching:

// 1. Host-driven preload — just hand the in-flight fetch to the loader.
const inflight = fetch('/dist/secondary.wasm');
new WasmSplitLoader({ /* ... */, secondary: inflight, strategy: 'eager' });

// 2. Pre-compiled at boot — skip compile on the critical path.
const secondaryModule = await WebAssembly.compileStreaming(
  fetch('/dist/secondary.wasm'),
);
new WasmSplitLoader({ /* ... */, secondary: secondaryModule });

// 3. Fully deferred — thunk is only invoked on the first cold hit.
new WasmSplitLoader({
  /* ... */,
  secondary: () => fetch('/dist/secondary.wasm'),
  strategy: 'on-demand',
});

API

new WasmSplitLoader(options)

Top-level options (common to both modes):

option type description
primary WasmSource (string | URL | Response | Promise<Response> | ArrayBuffer | Uint8Array) Primary wasm source. Always fetched eagerly.
imports WebAssembly.Imports User imports passed through to primary.
fetch typeof fetch Override fetch — used by the test harness.
onColdHit (ev: ColdHitEvent) => void Telemetry hook fired on every stub entry. ev is a discriminated union: { mode: 'split', tableId, secondaryReady } or { mode: 'archive', tableId, trampolinesReady }.

The constructor is fail-fast: it validates options synchronously (mutual exclusion of split / archive, required fields, manifest schema_version) and throws before any I/O happens.

WasmSplitLoader is generic over exports — new WasmSplitLoader<MyExports>({...}) narrows inst.exports to your declared type.

Split-mode only (mutually exclusive with archive):

option type description
secondary DeferredWasmSource — any WasmSource, WebAssembly.Module, Promise of either, or a zero-arg thunk returning any of the above Secondary wasm. Thunks are only invoked when the load actually happens, which pairs with strategy: 'on-demand'.
manifest SplitManifest Parsed split-manifest.json object. Fetch + parse it yourself before passing in.
strategy 'eager' | 'lazy' | 'on-demand' When to start fetching secondary. Default 'eager'. See "Loading strategies" above.

Archive-mode only (mutually exclusive with secondary / manifest / strategy):

option type description
archive.source WasmSource WSAR archive bytes.
archive.manifest ArchiveManifest Parsed archive-manifest.json object (validated against schema_version synchronously).
archive.trampolineFill 'eager' | 'incremental' | 'manual' See the trampolineFill table above. Default 'eager'.
archive.batchSize number Overrides the manifest's batch_size.
archive.bodyImports WebAssembly.Imports Extra imports to merge into every body micro-module. Useful when cold functions import host functions that aren't re-exported by primary.
archive.decompressBrotli (bytes: Uint8Array, uncompressedSize: number) => Uint8Array Synchronous Brotli decoder. Required when the archive is per_function_brotli: true and the host lacks native synchronous Brotli decoding — the loader prints a one-shot warning if it detects this situation.

loader.instantiate() → Promise<WasmSplitInstance>

WasmSplitInstance is a discriminated union on mode:

type WasmSplitInstance<T = WebAssembly.Exports> =
  | {
      mode: 'split';
      instance: WebAssembly.Instance;
      exports: T;
      secondaryReady: Promise<void>;
      isSecondaryReady(): boolean;
      loadSecondary(): Promise<void>;
    }
  | {
      mode: 'archive';
      instance: WebAssembly.Instance;
      exports: T;
      secondaryReady: Promise<void>;      // resolves after trampoline fill
      isSecondaryReady(): boolean;
      loadSecondary(): Promise<void>;     // same promise as secondaryReady
      archive: WasmArchiveLoader;         // non-nullable in archive mode
      archiveFillReport: FillTrampolinesReport;
    };
  • Split mode: loadSecondary() is idempotent and returns the in-flight promise on subsequent calls.
  • Archive mode: secondaryReady resolves once trampolines have been installed per trampolineFill; loadSecondary() returns the same promise. archive / archiveFillReport are guaranteed to be present and non-null once the union has narrowed to mode: 'archive'.

WasmArchiveLoader (returned as instance.archive)

method / property description
fillTableWithTrampolines(options?) Install one trampoline (de-duplicated by type signature) per cold slot. Returns { compiledModules, filledSlots }. async. Pass options.incremental: true to yield to the event loop between type-groups.
injectByTableIndexSync(slot) Compile the body micro-module for slot's batch, new WebAssembly.Instance, active-elem overwrite every slot in the batch. Runs fully synchronously — this is what the trampoline's wait handler calls under the hood. Idempotent.
injectByTableIndex(slot) Async wrapper around the sync version; convenient for pre-warming.
evictByTableIndex(slot) Batch-level evict: restore trampolines for every slot in slot's batch and drop the shared WebAssembly.Instance reference so GC can reclaim the JIT. Returns true if anything was evicted.
handleWait() Implementation of the wait import used by trampolines; already wired up by the loader.
archive / manifest Parsed archive / manifest metadata.

Errors

  • SecondaryNotReadyError — split-mode-only: a cold function ran before secondary was loaded. Never thrown in archive mode (injection is synchronous). Always await secondaryReady first.
  • IncompatiblePrimaryError — the primary module is missing the expected memory / table exports. Almost always means the primary was built with a different wasm-split version than this runtime.

Profile-time helper

When you instrument a wasm with wasm-split prepare (the profile-collection mode), the instrumented module imports wasm_split_prepare.report and optionally wasm_split_prepare.bitmap. This package ships a tiny helper:

import { createPrepareClient } from '@wasm-split/runtime/prepare';

const client = createPrepareClient({
  endpoint: 'http://127.0.0.1:9876/report', // wasm-split collect
  bitmapPages: 1, // from prepare-manifest.json
});

const { instance } = await WebAssembly.instantiate(wasmBytes, {
  env: { /* ... */ },
  wasm_split_prepare: client.imports,
});

// ...play through the hot path...
await client.flush();

End-to-end workflow

            ┌──────────────────┐
            │ wasm-split       │
1. profile  │   prepare        │  emits instrumented.wasm + prepare-client.js
            └────────┬─────────┘
                     │
                     v
            ┌──────────────────┐
            │ runtime in       │  uses createPrepareClient -> POST /report
            │ browser session  │
            └────────┬─────────┘
                     │
                     v
            ┌──────────────────┐
            │ wasm-split       │  accumulates fids -> hot-funcidx.txt
2. collect  │   collect        │
            └────────┬─────────┘
                     │
                     v
            ┌──────────────────┐
            │ wasm-split       │  cold = local - hot
3. split    │   split          │  split mode: primary.wasm + secondary.wasm
            │                  │  archive mode: primary.archive.wasm +
            │                  │                func_archive.bin
            └────────┬─────────┘
                     │
                     v
            ┌──────────────────┐
            │ WasmSplitLoader  │
4. ship     │   in production  │
            └──────────────────┘

Compatibility

  • All evergreen browsers (Chrome / Edge / Firefox / Safari) with WebAssembly.instantiateStreaming.
  • Node 18+ (for SSR / test). The runtime falls back to WebAssembly.instantiate(arrayBuffer) when streaming fails on Node-style responses.

License

MIT.

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.