js_web

    web standard api bindings (fetch, Streams, Blob, URL, Crypto, ...)

    js
    web
    fetch
    streams
    dom
    Download zip
    Author
    Version
    0.13.1
    License
    MIT
    Last updated
    2 hours ago
    Downloads
    23

    #mizchi/js_web

    Web Standard API bindings for MoonBit, providing universal, platform-independent access to standardized Web APIs.

    These APIs work consistently across:
    • Browsers (Chrome, Firefox, Safari, Edge)
    • Server-side runtimes (Node.js 18+, Deno, Bun)
    • Edge runtimes (Vercel Edge, Netlify Edge, and others)
    • Any WinterCG-compliant runtime

    #Web API Support Status

    APIPackageStatusNote
    HTTP & Networking
    fetchmizchi/js_web/http๐Ÿงช TestedHTTP requests
    Requestmizchi/js_web/http๐Ÿงช TestedRequest objects
    Responsemizchi/js_web/http๐Ÿงช TestedResponse objects
    Headersmizchi/js_web/http๐Ÿงช TestedHTTP headers
    FormDatamizchi/js_web/http๐Ÿงช TestedForm data handling
    URLmizchi/js_web/url๐Ÿงช TestedURL parsing
    URLSearchParamsmizchi/js_web/url๐Ÿงช TestedQuery strings
    URLPatternmizchi/js_web/url๐Ÿงช TestedURL pattern matching
    WebSocketmizchi/js_web/websocket๐Ÿงช TestedWebSocket API
    Streams
    ReadableStreammizchi/js_web/streams๐Ÿงช TestedReadable streams
    WritableStreammizchi/js_web/streams๐Ÿงช TestedWritable streams
    TransformStreammizchi/js_web/streams๐Ÿงช TestedTransform streams
    CompressionStreammizchi/js_web/streams๐Ÿงช TestedGZIP/Deflate compression
    DecompressionStreammizchi/js_web/streams๐Ÿงช TestedGZIP/Deflate decompression
    Binary Data
    Blobmizchi/js_web/blob๐Ÿงช TestedBinary data
    Filemizchi/js_web/file๐Ÿงช TestedBlob with a name and mtime
    FileReadermizchi/js_web/file๐Ÿงช TestedRead a Blob as text/ArrayBuffer/data URL
    Encoding
    TextEncodermizchi/js_web/encoding๐Ÿงช TestedString to Uint8Array
    TextDecodermizchi/js_web/encoding๐Ÿงช TestedUint8Array to String
    Events
    Eventmizchi/js_web/event๐Ÿงช TestedEvent objects
    CustomEventmizchi/js_web/event๐Ÿงช TestedCustom events
    MessageEventmizchi/js_web/event๐Ÿงช TestedMessage events
    Cryptography
    Cryptomizchi/js_web/crypto๐Ÿ†— ReviewedWeb Crypto API
    SubtleCryptomizchi/js_web/crypto๐Ÿค– AI GeneratedCryptographic operations
    Workers & Concurrency
    Workermizchi/js_web/worker๐Ÿงช TestedWeb Workers
    MessagePortmizchi/js_web/worker๐Ÿงช TestedMessage passing
    MessageChannelmizchi/js_web/message๐Ÿงช TestedChannel messaging
    WebAssembly
    WebAssemblymizchi/js_web/webassembly๐Ÿค– AI GeneratedWASM integration
    WebGPU
    WebGPUmizchi/js_web/webgpu๐Ÿงช TestedAll 35 GPU* interfaces, incl. canvas rendering
    WebNN
    WebNNmizchi/js_web/nn๐Ÿงช Testednavigator.ml, graph building, device tensors
    WebGL
    WebGLmizchi/js_web/webgl๐Ÿ“… Planned2D/3D graphics rendering
    WebGL2mizchi/js_web/webgl๐Ÿ“… PlannedWebGL 2.0 API
    WebTransport
    WebTransportmizchi/js_web/webtransport๐Ÿ“… PlannedHTTP/3 based transport

    #Status Legend

    • ๐Ÿ†— Reviewed: Human reviewed (AI agents cannot change this status)
    • ๐Ÿงช Tested: Comprehensive test coverage
    • ๐Ÿงช Experimental: Early stage, limited platform support
    • ๐Ÿค– AI Generated: FFI bindings created, needs testing
    • ๐Ÿ“… Planned: Scheduled for future implementation

    #Overview

    This package provides comprehensive bindings to Web Standard APIs - the common subset of APIs standardized by WHATWG and W3C that work universally across JavaScript runtimes.

    Classification follows WinterCG (Web-interoperable Runtimes Community Group) definitions, specifically the Minimum Common Web Platform API specification. APIs in mizchi/js_web/* are platform-independent and work across browsers, Node.js, Deno, Bun, and edge runtimes.

    #Why Use web/* Packages?

    • Write Once, Run Anywhere: Code using these APIs works in browsers, Node.js, Deno, and other modern runtimes
    • Server-Side JavaScript: Build backend services with the same APIs you use in the browser
    • Edge Computing: Deploy to edge runtimes without platform-specific code
    • Future-Proof: Based on living standards that continue to evolve
    • Type-Safe: MoonBit's type system ensures compile-time safety
    • Well-Tested: Comprehensive test coverage across environments

    #Included APIs

    • HTTP/Networking: fetch, Request/Response, Headers, FormData, URL APIs, WebSocket
    • Streams: ReadableStream, WritableStream, TransformStream for efficient data processing
    • Cryptography: Web Crypto API for secure operations (hashing, encryption, key generation)
    • Workers: Web Workers and MessageChannel for concurrency (browser and Node.js)
    • WebGPU: GPU compute and rendering โ€” every GPU* interface, including GPUCanvasContext for drawing to a canvas. Browsers expose it directly; Deno needs --unstable-webgpu.
    • WebNN: neural-network inference via navigator.ml โ€” graph building, compilation and device tensors. Model formats and runtimes live a layer up, in mizchi/webnn-mbt.

    #Installation

    Add to your moon.mod:

    import { "mizchi/js_core@0.13.0", "mizchi/js_web@0.13.0", }

    ...and pick the sub-packages you need in the moon.pkg of the package that uses them:

    import { "mizchi/js_core" @core, "mizchi/js_web/blob", "mizchi/js_web/crypto", "mizchi/js_web/encoding", "mizchi/js_web/event", "mizchi/js_web/http", "mizchi/js_web/streams", "mizchi/js_web/url", "mizchi/js_web/webassembly", "mizchi/js_web/webgpu", "mizchi/js_web/websocket", "mizchi/js_web/worker", }

    Note: The mizchi/js_web package itself is a meta-package. You need to import specific sub-packages (like mizchi/js_web/http, mizchi/js_web/crypto, etc.) to use their APIs. There is no "wildcard import" in MoonBit - each sub-package must be imported explicitly.

    #Usage Examples

    #Fetch API (Universal - Browser & Server)

    // Simple GET request - works in browser, Node.js, Deno, and edge runtimes let response = @http.fetch("https://api.example.com/data") let json = response.json() // POST request with JSON body let request = @http.Request("https://api.example.com/users", method="POST", body="{\"name\":\"Alice\"}", headers=headers ) let response = @http.fetch_with_request(request) // Server-side API handler example (Cloudflare Workers, Vercel Edge, etc.) fn handle_request(request : @http.Request) -> @http.Response { let url = request.url() if url.pathname == "/api/hello" { @http.Response( body="{\"message\":\"Hello World\"}", status=200, headers=... ) } else { @http.Response(body="Not Found", status=404) } }

    #Streams (Server-Side Data Processing)

    // Streaming API responses - efficient for large datasets
    fn stream_large_file(file_path : String) -> @http.Response {
    let stream = @streams.ReadableStream(...)
    @http.Response(
    body=stream,
    headers=...
    )
    }

    // Transform streams for data processing pipelines
    fn process_stream(input : @streams.ReadableStream) -> @streams.ReadableStream {
    let transform = @streams.TransformStream()
    input.pipe_through(transform)
    }

    // Server-sent events (SSE) example
    fn create_sse_stream() -> @streams.ReadableStream {
    @streams.ReadableStream(controller => {
    // Send periodic updates
    controller.enqueue("data: {\"time\": \"...\"}\n\n")
    })
    }

    // Compression streams - compress data on the fly
    fn compress_response(data : String) -> @streams.ReadableStream {
    let compressor = @streams.CompressionStream("gzip")
    let encoder = @encoding.TextEncoder()

    // Create a readable stream from data
    let readable = create_stream_from_string(data)

    // Pipe through compression
    readable.pipeThrough(compressor)
    compressor.readable()
    }

    // Decompression streams - decompress streamed data
    fn decompress_request(compressed_stream : @streams.ReadableStream) -> @streams.ReadableStream {
    let decompressor = @streams.DecompressionStream("gzip")
    compressed_stream.pipeThrough(decompressor)
    decompressor.readable()
    }

    #Web Crypto (Secure Server-Side Operations)

    // Password hashing (server-side authentication)
    async fn hash_password(password : String) -> @arraybuffer.ArrayBuffer {
    let subtle = @crypto.Crypto::get().subtle
    let data = @encoding.TextEncoder().encode(password)
    subtle.digest("SHA-256", data.as_any())
    }

    // Generate JWT tokens (API authentication)
    async fn sign_jwt(payload : String, secret : String) -> @arraybuffer.ArrayBuffer {
    let subtle = @crypto.Crypto::get().subtle
    let encoder = @encoding.TextEncoder()

    // Algorithm descriptors are plain JS objects
    let algorithm = @core.from_entries([
    ("name", @core.any("HMAC")),
    ("hash", @core.any("SHA-256")),
    ])

    // Import the HMAC key, then sign
    let key = subtle.import_key(
    "raw",
    encoder.encode(secret).as_any(),
    algorithm,
    false,
    ["sign"],
    )
    subtle.sign(algorithm, key.as_any(), encoder.encode(payload).as_any())
    }

    // Encrypt sensitive data (database encryption)
    async fn encrypt_data(data : String) -> @arraybuffer.ArrayBuffer {
    let subtle = @crypto.Crypto::get().subtle

    // Generate an AES-GCM key
    let key = subtle.generate_key(
    @core.from_entries([
    ("name", @core.any("AES-GCM")),
    ("length", @core.any(256)),
    ]),
    true,
    ["encrypt", "decrypt"],
    )

    // Encrypt -- AES-GCM needs a 12-byte iv
    let iv = @crypto.Crypto::get().getRandomValues(
    @arraybuffer.Uint8Array::from_size(12),
    )
    let algorithm = @core.from_entries([
    ("name", @core.any("AES-GCM")),
    ("iv", iv.as_any()),
    ])
    subtle.encrypt(algorithm, key, @encoding.TextEncoder().encode(data).as_any())
    }

    There is no AesKeyGenParams type โ€” Web Crypto algorithm descriptors are passed as ordinary JS objects built with @core.from_entries.

    #WebSocket (Real-Time Communication)

    // Client-side (browser) or server-side (Node.js, Bun)
    let ws = @websocket.WebSocket("wss://api.example.com/ws")

    ws.addEventListener("open", fn(event) {
    ws.send("{\"type\":\"subscribe\",\"channel\":\"updates\"}")
    })

    ws.addEventListener("message", fn(event) {
    let data = event.data()
    // Process real-time updates
    console.log(data)
    })

    ws.addEventListener("error", fn(event) {
    console.error("WebSocket error")
    })

    // Cloudflare Workers Durable Objects WebSocket example
    fn handle_websocket(request : @http.Request) -> @http.Response {
    let upgrade = request.headers()._get("Upgrade")
    if upgrade == Some("websocket") {
    // Upgrade connection to WebSocket
    // Handle WebSocket messages
    }
    @http.Response(body="Not a WebSocket request", status=400)
    }

    #Web Workers

    let worker = @worker.Worker("worker.js")

    worker.addEventListener("message", fn(event) {
    let result = event.data()
    console.log(result)
    })

    worker.postMessage("Start processing")

    #Common Use Cases

    #๐ŸŒ Universal API Client

    Build HTTP clients that work in any environment:
    // Same code runs in browser, Node.js, Deno, Cloudflare Workers
    fn fetch_user(id : Int) -> @js.Promise[@core.Any] {
    let response = @http.fetch("https://api.example.com/users/\(id)")
    response.json()
    }

    #๐Ÿ” Authentication & Security

    Handle authentication uniformly across platforms:
    fn verify_jwt(token : String) -> Bool {
    // Web Crypto works everywhere
    let crypto = @crypto.get_crypto()
    // Verify signature
    }

    #๐Ÿ“ก Edge Computing

    Build edge functions with standard APIs:
    // Deploy to Cloudflare Workers, Vercel Edge, Netlify Edge
    fn handle(request : @http.Request) -> @http.Response {
    let path = request.url().pathname
    match path {
    "/api/data" => fetch_and_transform_data()
    _ => @http.Response(body="Not Found", status=404)
    }
    }

    #๐Ÿ”„ Data Streaming

    Process large datasets efficiently:
    // Stream processing works on server and client
    fn process_large_file(url : String) -> @stream.ReadableStream {
    let response = @http.fetch(url)
    response.body()
    }

    #๐Ÿ’ฌ Real-Time Communication

    WebSocket works in all environments:
    // Same code for browser client and Node.js backend
    fn connect_to_server() -> @websocket.WebSocket {
    @websocket.WebSocket("wss://api.example.com/ws")
    }

    #Platform Compatibility

    APIBrowserNode.jsDenoBunCloudflare WorkersVercel Edge
    fetchโœ…โœ… (18+)โœ…โœ…โœ…โœ…
    Request/Responseโœ…โœ… (18+)โœ…โœ…โœ…โœ…
    Headersโœ…โœ… (18+)โœ…โœ…โœ…โœ…
    URLโœ…โœ…โœ…โœ…โœ…โœ…
    WebSocketโœ…โœ…โœ…โœ…โœ…โœ…
    Streamsโœ…โœ… (16+)โœ…โœ…โœ…โœ…
    Web Cryptoโœ…โœ… (15+)โœ…โœ…โœ…โœ…
    Workersโœ…โœ… (10+)โœ…โœ…โœ… (Durable Objects)โŒ
    WebGPUโœ…โŒโœ… (unstable)โŒโŒโŒ

    #When to Use web/* vs Other Packages

    #Use mizchi/js_web/* when:

    • โœ… Building cross-platform libraries
    • โœ… Writing code for edge computing (Cloudflare Workers, Vercel Edge)
    • โœ… Creating universal API clients
    • โœ… Need standard HTTP/fetch APIs
    • โœ… Working with streams for data processing
    • โœ… Implementing authentication/cryptography

    #Use mizchi/js_browser/* when:

    • ๐ŸŒ Manipulating the DOM (Document, Element, Events)
    • ๐ŸŒ Browser-specific APIs (Window, Navigator, Storage)
    • ๐ŸŒ Canvas rendering
    • ๐ŸŒ Browser-only features (MutationObserver, etc.)

    #Use mizchi/js_node/* when:

    • ๐ŸŸข Accessing file system (fs)
    • ๐ŸŸข Process management (child_process)
    • ๐ŸŸข Node.js-specific modules (path, os, etc.)

    #Use mizchi/js/cloudflare/* when:

    • โšก Using Cloudflare Workers APIs (KV, D1, R2)
    • โšก Durable Objects
    • โšก Workers-specific features

    • mizchi/js - Core JavaScript FFI and built-in objects
    • mizchi/js_browser/dom - Browser-specific DOM and rendering APIs
    • mizchi/js_node - Node.js-specific runtime APIs
    • mizchi/js/cloudflare - Cloudflare Workers platform APIs
    • mizchi/js_deno - Deno runtime APIs (separate module)

    #Standards Compliance

    All APIs follow official WHATWG and W3C specifications, ensuring compatibility across JavaScript runtimes:

    These bindings follow WinterCG (Web-interoperable Runtimes Community Group) standards, specifically:

    #License

    See the main project license.

    Powered by MoonBit

    Site sourceReport issuePackagesBuild queueSkillsStatistics

    ยฉ 2026 mooncakes.io