npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

milost

v3.7.21

Published

A Rust-like TypeScript library with WebAssembly optimizations

Readme

MiLost 🚀

High-performance TypeScript framework with WebGL/Canvas rendering and comprehensive WASM acceleration

npm version TypeScript WebAssembly WebGL License: MIT

MiLost is a comprehensive TypeScript framework that brings Rust-inspired data structures, high-performance algorithms, multithreading capabilities, and WebGL-accelerated UI rendering to JavaScript, all powered by WebAssembly for maximum performance.

✨ Key Features

  • 🦀 Complete Type System - Option<T>, Result<T, E>, Vec<T>, HashMap<K, V>, smart pointers
  • WASM Acceleration - 32/36 modules using WASM (89% coverage) with 10-100x performance gains
  • 🧵 Intelligent Threading - Dynamic worker pools with SharedArrayBuffer support
  • 🎯 SIMD Optimization - 1.7-4.5x speedup with automatic browser capability detection
  • 🎨 WebGL UI Rendering - Hardware-accelerated rendering with shaders and orthographic projection
  • 🤖 Machine Learning - K-means, PCA, decision trees, linear regression (WASM-powered)
  • 🔐 Cryptography & Compression - AES-GCM, SHA-256/512, HMAC, Gzip, Huffman coding
  • 📊 Advanced Algorithms - Sorting, searching, graph algorithms with automatic optimization
  • 🧠 Reactive State Management - Atom-based system with middleware and framework adapters
  • 📦 Zero Configuration - Complete toolchain with hot reload, type safety, and deployment

🚀 Quick Start

Option 1: Create New Project (Recommended)

Create a production-ready application with full WASM + WebGL acceleration out of the box:

# Console application with data processing
npx create-milost-app my-app

# Web application with WebGL UI rendering
npx create-milost-app my-app --ui

cd my-app
npm run dev  # Starts with hot reload, WASM threading, and WebGL rendering

What you get out of the box:

  • WASM acceleration with SIMD support
  • SharedArrayBuffer threading enabled
  • WebGL rendering pipeline ready
  • Hot reload development server
  • TypeScript configured
  • Zero configuration needed

Generated project structure:

my-app/
├── src/
│   ├── main.ts              # Clean entry point
│   ├── internal/bootstrap.ts # WASM + WebGL initialization
│   └── views/MainView.ts     # WebGL UI components
├── public/index.html         # (UI mode only)
└── tsconfig.json            # TypeScript config

Option 2: Add to Existing Project

npm install milost

📊 Performance & Capabilities

WASM-Accelerated Performance

| Operation | JavaScript | MiLost (WASM) | Speedup | | ------------------------ | ---------- | ------------- | -------------- | | Vec batch operations | 50ms | 0.8ms | 62x faster | | HashMap operations | 12ms | 0.3ms | 40x faster | | Sorting algorithms | 100ms | 2.1ms | 48x faster | | Machine learning | 500ms | 15ms | 33x faster | | Cryptographic operations | 200ms | 5ms | 40x faster |

Browser Compatibility & Features

| Feature | Browser Support | Performance Gain | | --------------------------- | --------------- | -------------------- | | Basic WASM | 100% | 10-50x baseline | | SIMD acceleration | 85%+ | +1.7-4.5x | | SharedArrayBuffer threading | ~70% | +1.8-2.9x | | Automatic fallbacks | 100% | Graceful degradation |

🗄️ Data Structures & Core Types

All data structures have WASM implementations with JavaScript fallbacks:

Collections

import { Vec, HashMap, HashSet, Option, Result } from "milost";

// High-performance vectors with batch operations
const vec = Vec.from([1, 2, 3, 4, 5]);
const doubled = vec.batchMap((x) => x * 2); // 96.4x faster than regular map
const sum = vec.batchReduce((a, b) => a + b, 0);

// Mutable collections for performance-critical operations
const mutVec = Vec.mut<number>();
for (let i = 0; i < 10000; i++) {
  mutVec.push(i); // O(1) in-place operation
}
const immutableResult = mutVec.freeze();

// Hash-based collections
const map = HashMap.from([
  ["users", 1000],
  ["posts", 5000],
]);
const userCount = map.get("users").unwrapOr(0);

// Set operations
const set1 = HashSet.from([1, 2, 3, 4]);
const set2 = HashSet.from([3, 4, 5, 6]);
const intersection = set1.intersection(set2); // {3, 4}

Safe Programming with Option & Result

// Never deal with null/undefined again
function findUser(id: string): Option<User> {
  const user = database.find(id);
  return user ? Option.Some(user) : Option.None();
}

const user = findUser("123")
  .map((u) => u.name.toUpperCase())
  .filter((name) => name.length > 3)
  .unwrapOr("Anonymous");

// Explicit error handling without exceptions
function divide(a: number, b: number): Result<number, string> {
  return b === 0 ? Result.Err("Division by zero") : Result.Ok(a / b);
}

const result = divide(10, 2)
  .map((x) => x * 100)
  .andThen((x) => (x > 1000 ? Result.Ok(x) : Result.Err("Too small")))
  .unwrapOr(0);

Type-Safe Primitives

import { validateU32, add_u32, bitwise_and } from "milost";

// Compile-time and runtime type safety
const safeNumber = validateU32(42); // Result<u32, ValidationError>
const sum = add_u32(100, 200); // WASM-accelerated arithmetic
const masked = bitwise_and(0xff, 0x0f); // Bitwise operations

🧵 Advanced Threading & Performance

Intelligent Worker Pool System

MiLost automatically chooses the optimal execution strategy:

import { Algorithms, Compression, Crypto } from "milost";

// Small datasets: runs synchronously
const smallSort = await Algorithms.quickSort([5, 2, 8, 1]);

// Medium datasets: uses Web Workers automatically
const mediumSort = await Algorithms.quickSort(
  Array.from({ length: 50000 }, () => Math.random())
);

// Large datasets: uses WASM threading with SharedArrayBuffer (if available)
const largeSort = await Algorithms.quickSort(
  Array.from({ length: 500000 }, () => Math.random())
);

// Same intelligent scaling for all operations
const compressed = await Compression.gzip(largeData); // Auto-threading
const hashed = await Crypto.sha256(hugeFile); // WASM + threads

Performance Thresholds (Automatic)

  • Synchronous: < 1000 items
  • Web Workers: 1000-50000 items
  • WASM Threading: 50000+ items (when SharedArrayBuffer available)

🔧 High-Performance Algorithms

All algorithms are WASM-accelerated with intelligent optimization:

Sorting & Searching

import { Algorithms } from "milost";

// Intelligent algorithm selection based on data characteristics
const sorted = await Algorithms.quickSort([64, 34, 25, 12, 22, 11, 90]);
const mergeSort = await Algorithms.mergeSort(data); // Stable sort
const radixSort = await Algorithms.radixSort(integers); // Integer-only, very fast

// Optimized search algorithms
const found = Algorithms.binarySearch([1, 3, 5, 7, 9], 5); // Some(2)
const linear = Algorithms.linearSearch(unsorted, target);

Graph Algorithms

import { Graph } from "milost";

const graph = Graph.new();
graph.addEdge("A", "B", 4);
graph.addEdge("B", "C", 2);
graph.addEdge("A", "C", 7);

// Dijkstra's shortest path (WASM-accelerated)
const path = graph.dijkstra("A", "C"); // ["A", "B", "C"] with distance 6

// Other graph operations
const bfsResult = graph.breadthFirstSearch("A");
const topologicalOrder = graph.topologicalSort();

Cryptography & Security

import { Crypto } from "milost";

// Hardware-accelerated hashing
const hash = await Crypto.sha256("sensitive data");
const hmac = await Crypto.hmac("message", "secret_key");

// AES-GCM encryption with secure key generation
const key = Crypto.generateKey(); // Cryptographically secure
const encrypted = await Crypto.encrypt("secret message", key);
const decrypted = await Crypto.decrypt(encrypted, key);

Compression

import { Compression } from "milost";

// Automatic format detection and optimization
const compressed = await Compression.gzip(data);
const huffman = await Compression.huffman(text); // Optimal for text
const lz77 = await Compression.lz77(binaryData); // Good for binary

// Streaming compression for large files
const stream = Compression.createGzipStream();
stream.write(chunk1);
stream.write(chunk2);
const result = stream.finish();

🤖 Machine Learning (WASM-Powered)

Complete ML suite with WASM acceleration:

Clustering

import { KMeans } from "milost";

const data = [
  [1, 2],
  [2, 1],
  [8, 7],
  [9, 8],
  [7, 9],
];
const kmeans = KMeans.new(2); // 2 clusters

const result = await kmeans.fit(data);
console.log(result.centroids); // Cluster centers
console.log(result.assignments); // Point assignments
console.log(result.inertia); // Quality metric

Classification

import { DecisionTree } from "milost";

const features = [
  [1, 2],
  [2, 3],
  [3, 1],
  [4, 5],
];
const labels = [0, 0, 1, 1];

const tree = DecisionTree.new({ maxDepth: 5 });
await tree.fit(features, labels);

const predictions = tree.predict([[2.5, 2.5]]); // [0] or [1]
const accuracy = tree.score(testFeatures, testLabels);

Regression & Dimensionality Reduction

import { LinearRegression, PCA } from "milost";

// Linear regression with multiple features
const X = [
  [1, 2],
  [2, 3],
  [3, 4],
  [4, 5],
];
const y = [2.1, 3.9, 6.1, 8.0];

const lr = LinearRegression.new();
await lr.fit(X, y);
const predictions = lr.predict([[5, 6]]); // [~10.0]

// Principal Component Analysis
const pca = PCA.new(2); // Reduce to 2 components
const transformed = await pca.fitTransform(highDimData);
console.log(pca.explainedVariance); // Variance explained by each component

🎨 Canvas-Based UI System

Modern UI components with pure canvas rendering and builder pattern:

Architecture

TypeScript API → WASM Components → Canvas Commands → Direct Canvas Rendering

No DOM manipulation - everything rendered directly to canvas for maximum performance.

Component Usage

import { View, VStack, HStack, Text, Button, UIEngine } from "milost";

export class MainView implements ViewProtocol {
  private engine: UIEngine | null = null;

  async render(): Promise<void> {
    this.engine = new UIEngine();

    // Builder pattern - chain method calls to construct UI
    const layout = new View()
      .addChild(
        new VStack() // Vertical layout container
          .addChild(
            new Text().updateProperties({
              content: "Welcome to MiLost",
              fontSize: "32",
              fontWeight: "bold",
              color: "#333333",
            })
          )
          .addChild(
            new HStack() // Horizontal layout container
              .addChild(
                new Button()
                  .updateProperties({
                    title: "Cancel",
                    backgroundColor: "#666666",
                  })
                  .onTap(() => console.log("Cancel clicked"))
              )
              .addChild(
                new Button()
                  .updateProperties({
                    title: "Confirm",
                    backgroundColor: "#007AFF",
                  })
                  .onTap(() => console.log("Confirmed"))
              )
              .updateProperties({
                spacing: "16px",
                alignment: "center",
              })
          )
          .updateProperties({
            spacing: "24px",
            alignment: "center",
            padding: "40px",
          })
      )
      .updateProperties({
        width: "100%",
        height: "100vh",
        backgroundColor: "#f8f9fa",
      });

    // Mount to canvas with WASM acceleration
    const container = document.getElementById("app");
    this.engine.mount(layout, container);
  }
}

Available Components

| Component | Purpose | Key Methods | | ------------- | ------------------ | ------------------------------------------------------------- | | View | Base container | .backgroundColor(), .padding(), .width(), .height() | | VStack | Vertical layout | .addChild(), .updateProperties({ spacing, alignment }) | | HStack | Horizontal layout | .addChild(), .updateProperties({ spacing, alignment }) | | ZStack | Layered layout | .addChild() (depth-based rendering) | | Text | Text display | .updateProperties({ content, fontSize, color, fontWeight }) | | Button | Interactive button | .updateProperties(), .onTap(), .onHover() | | TextField | Text input | .updateProperties(), .onChange(), .onFocus() | | Toggle | Switch control | .updateProperties(), .onToggle() | | Slider | Range input | .updateProperties(), .onChange() |

UI Benefits

  1. Pure Canvas Rendering - No DOM manipulation overhead
  2. Builder Pattern - Intuitive, chainable API similar to SwiftUI
  3. WASM Acceleration - Layout calculations in Rust for performance
  4. High DPI Support - Automatic device pixel ratio handling
  5. Event System - Efficient canvas-coordinate based events

🧠 Reactive State Management

Comprehensive state system with framework adapters:

Atoms & Reactive State

import { atom, selector, AtomStore } from "milost";

// Reactive state containers
const countAtom = atom(0);
const doubledCount = selector((get) => get(countAtom) * 2);

// Subscribe to changes
countAtom.subscribe((count) => console.log("Count:", count));

// Update state
countAtom.set(5); // Triggers subscribers
console.log(doubledCount.get()); // 10

// Advanced state management
const store = AtomStore.create();
const userAtom = store.atom({ id: 1, name: "John" });
const userNameAtom = store.selector((get) => get(userAtom).name);

Framework Integration

// React integration
import { useAtom, useAtomValue } from "milost/react";

function Counter() {
  const [count, setCount] = useAtom(countAtom);
  const doubled = useAtomValue(doubledCount);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Doubled: {doubled}</p>
      <button onClick={() => setCount((c) => c + 1)}>Increment</button>
    </div>
  );
}

// Vue integration
import { useAtom } from "milost/vue";

export default {
  setup() {
    const [count, setCount] = useAtom(countAtom);
    return { count, setCount };
  },
};

🔧 Memory Management & Smart Pointers

Rust-inspired memory safety patterns:

import { Rc, Arc, RefCell, Mutex, RwLock } from "milost";

// Reference counting for shared ownership
const shared = Rc.new({ data: "shared resource" });
const clone1 = shared.clone(); // Reference count: 2
const clone2 = shared.clone(); // Reference count: 3

// Thread-safe reference counting
const threadSafe = Arc.new([1, 2, 3, 4, 5]);
const workers = Array.from({ length: 4 }, () => {
  const clonedArc = threadSafe.clone();
  return new Worker(/* ... */); // Each worker gets shared access
});

// Interior mutability
const cell = RefCell.new(42);
const borrowed = cell.borrow_mut();
borrowed.update((value) => value * 2); // Safe mutation

// Thread-safe mutability
const mutex = Mutex.new(Vec.new());
await mutex.lock().then((vec) => {
  vec.push(1);
  vec.push(2);
  vec.push(3);
});

🔄 Pattern Matching

Rust-style pattern matching for control flow:

import { match, _, __ } from "milost";

const result = Option.Some(42);

const output = match(result)
  .with({ Some: 42 }, () => "Exactly 42!")
  .with({ Some: _ }, (value) => `Some value: ${value}`)
  .with({ None: _ }, () => "No value")
  .exhaustive(); // Compile-time exhaustiveness checking

// Advanced patterns
const complexMatch = match(data)
  .when(
    (x) => x > 100,
    (x) => `Large: ${x}`
  )
  .when(
    (x) => x > 50,
    (x) => `Medium: ${x}`
  )
  .when(
    (x) => x > 0,
    (x) => `Small: ${x}`
  )
  .otherwise(() => "Invalid");

📦 Complete Ecosystem

Published NPM Packages

  1. [email protected] - Core library with full WASM support
  2. [email protected] - Project scaffolding with templates
  3. [email protected] - Development server with CORS for SharedArrayBuffer
  4. [email protected] - Production builds and deployment tools

Development Features

# Hot reload development
npm run dev        # Automatic WASM rebuilding

# Multi-target WASM builds
npm run build:multi  # Basic, SIMD, and Full versions

# Production deployment
milost-build-tools deploy --platform vercel  # One-command deployment

# Performance analysis
milost-build-tools analyze --bundle --performance  # Detailed metrics

🚀 Real-World Examples

High-Performance Data Processing

import { Vec, HashMap, Algorithms, initWasm } from "milost";

await initWasm(); // Enable WASM acceleration

// Process millions of records efficiently
async function processLargeDataset(records: DataRecord[]) {
  // Use mutable collections for build phase
  const processed = Vec.mut<ProcessedRecord>();
  const index = HashMap.mut<string, number>();

  for (const record of records) {
    const transformed = transformRecord(record); // Your business logic
    processed.push(transformed);
    index.set(record.id, processed.length - 1);
  }

  // Convert to immutable for safe sharing
  const finalData = processed.freeze();
  const finalIndex = index.freeze();

  // Sort using WASM-accelerated algorithms (automatically multithreaded)
  const sorted = await Algorithms.quickSort(
    finalData.toArray(),
    (a, b) => a.timestamp - b.timestamp
  );

  return { data: sorted, index: finalIndex };
}

Real-Time Analytics Dashboard

import { atom, selector, Compression, Crypto } from "milost";

// Reactive state for real-time updates
const metricsAtom = atom<Metrics>({ users: 0, sessions: 0, revenue: 0 });
const trendsSelector = selector((get) => {
  const current = get(metricsAtom);
  return calculateTrends(current); // WASM-accelerated calculation
});

// Secure data compression for transmission
async function sendMetrics(metrics: Metrics) {
  const compressed = await Compression.gzip(JSON.stringify(metrics));
  const signature = await Crypto.hmac(compressed, secretKey);

  await fetch("/api/metrics", {
    method: "POST",
    body: compressed,
    headers: { "X-Signature": signature },
  });
}

// Subscribe to real-time updates
metricsAtom.subscribe((metrics) => {
  updateDashboard(metrics);
  sendMetrics(metrics); // Automatic compression + signing
});

Machine Learning Pipeline

import { KMeans, PCA, DecisionTree, LinearRegression } from "milost";

// Complete ML workflow with WASM acceleration
async function mlPipeline(rawData: number[][]) {
  // Dimensionality reduction
  const pca = PCA.new(10); // Reduce to 10 features
  const reducedData = await pca.fitTransform(rawData);

  // Clustering for data exploration
  const kmeans = KMeans.new(5); // 5 clusters
  const clusters = await kmeans.fit(reducedData);

  // Classification model training
  const features = clusters.data;
  const labels = clusters.assignments;

  const classifier = DecisionTree.new({ maxDepth: 10 });
  await classifier.fit(features, labels);

  // Regression for continuous predictions
  const regressor = LinearRegression.new();
  await regressor.fit(features, continuousTargets);

  return {
    clusters: clusters.centroids,
    classifier: classifier,
    regressor: regressor,
    explainedVariance: pca.explainedVariance,
  };
}

🎮 When to Use MiLost

Perfect For:

  • Data-intensive applications - Real-time analytics, financial platforms
  • Performance-critical systems - Gaming, trading, scientific computing
  • Secure applications - Cryptographic operations, data protection
  • Machine learning - Client-side ML, data analysis
  • Modern web UIs - When you want structured, performant components

Consider Alternatives For:

  • Simple websites - Static sites with minimal interactivity
  • Legacy browser support - IE11 or very old browsers
  • Tiny bundles - When every KB matters and performance isn't critical

📈 Bundle Size & Performance

Bundle Analysis

  • Core WASM: ~2.7MB (optimized with wee_alloc, LTO)
  • JavaScript wrapper: ~50KB (TypeScript API layer)
  • Compression: ~800KB gzipped (efficient for large applications)
  • Loading: <50ms initialization with lazy loading

Performance Characteristics

  • Cold start: <100ms (WASM compilation + initialization)
  • Hot path: 10-100x faster than pure JavaScript
  • Memory usage: Predictable, no GC pauses
  • Threading: Automatic scaling based on data size

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

📄 License

MIT © [MiLost Team]